.Net griglia delle proprietà. Esiste un modo per lasciare la Griglia manipolare oggetti in modo diverso

StackOverflow https://stackoverflow.com/questions/931644

Domanda

Come ho capito, La griglia struttura viene dato un oggetto che può manipolare estraendo le proprietà usando riflessioni.

Il mio problema è che ho una serie di parametri che viene determinato in fase di esecuzione, quindi non riesco a comporre staticly una classe con le proprietà per rappresentare questo insieme.

Ho due idea in mente per risolvere questo problema ma entrambi sono complesse e probabilmente consumano molto tempo, infatti devo dire che non sono pratici sotto i miei limiti di tempo. Uno è quello di utilizzare Reflection Emit al fine di definire una classe in modo dinamico e l'altro è quello di costruire dynamiclly un file sorgente C # e quindi compilarlo usando CodeDom.

Può griglia proprietà comportarsi in modo diverso (diverso quindi l'estrazione delle proprietà di un oggetto utilizzando riflessioni) che possono connessione internet il mio problema?

Se non si fa a sapere qualsiasi altro controllo che può fare il lavoro per me?

voglio dire che il motivo sono andato a griglia delle proprietà fin dall'inizio è stata la sua capacità di fornire davvero bello di reperimento dei dati utente per il colore types.For comune si autometically ottiene una tavolozza, per DataTime si dispone automaticamente un bel calendario. Vorrei ottenere automaticamente queste cose, se possibile.

È stato utile?

Soluzione

Sì, PropertyGrid in grado di visualizzare le cose altri che solo le proprietà in fase di compilazione, utilizzando uno qualsiasi dei TypeConverter, ICustomTypeDescriptor o TypeDescriptionProvider per fornire runtime pseudo-proprietà. Può fare un esempio di ciò che i parametri assomigliano? Dovrei essere in grado di fornire un esempio ...


Ecco un esempio di base (tutto è string, ecc) sulla base di una precedente risposta (correlato ma diverso):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
class PropertyBagPropertyDescriptor : PropertyDescriptor {
    public PropertyBagPropertyDescriptor(string name) : base(name, null) { }
    public override object GetValue(object component) {
        return ((PropertyBag)component)[Name];
    }
    public override void SetValue(object component, object value) {
        ((PropertyBag)component)[Name] = (string)value;
    }
    public override void ResetValue(object component) {
        ((PropertyBag)component)[Name] = null;
    }
    public override bool CanResetValue(object component) {
        return true;
    }
    public override bool ShouldSerializeValue(object component)
    { // *** this controls whether it appears bold or not; you could compare
      // *** to a default value, or the last saved value...
        return ((PropertyBag)component)[Name] != null;
    }
    public override Type PropertyType {
        get { return typeof(string); }
    }
    public override bool IsReadOnly {
        get { return false; }
    }
    public override Type ComponentType {
        get { return typeof(PropertyBag); }
    }
}
[TypeConverter(typeof(PropertyBagConverter))]
class PropertyBag {
    public string[] GetKeys() {
        string[] keys = new string[values.Keys.Count];
        values.Keys.CopyTo(keys, 0);
        Array.Sort(keys);
        return keys;
    }
    private readonly Dictionary<string, string> values
        = new Dictionary<string, string>();
    public string this[string key] {
        get {
            string value;
            values.TryGetValue(key, out value);
            return value;
        }
        set {
            if (value == null) values.Remove(key);
            else values[key] = value;
        }
    }
}
// has the job of (among other things) providing properties to the PropertyGrid
class PropertyBagConverter : TypeConverter {
    public override bool GetPropertiesSupported(ITypeDescriptorContext context) {
        return true; // are we providing custom properties from here?
    }
    public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes) {
        // get the pseudo-properties
        PropertyBag bag = (PropertyBag)value;
        string[] keys = bag.GetKeys();
        PropertyDescriptor[] props = Array.ConvertAll(
            keys, key => new PropertyBagPropertyDescriptor(key));
        return new PropertyDescriptorCollection(props, true);
    }
}

static class Program {
    [STAThread]
    static void Main() { // demo form app
        PropertyBag bag = new PropertyBag();
        bag["abc"] = "def";
        bag["ghi"] = "jkl";
        bag["mno"] = "pqr";
        Application.EnableVisualStyles();
        Application.Run(
            new Form {
                Controls = { new PropertyGrid {
                    Dock = DockStyle.Fill,
                    SelectedObject = bag
                }}
            });
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top