This example displays a custom collection/dictionary property in the DevExpress WPF Property Grid and allows users to add new items/entries as requirements/business needs dictate.
The following image illustrates available user actions:
To incorporate this feature in your DevExpress-powered WPF app (allow users to add new items to a collection/dictionary), set one of the following properties to true
:
- PropertyGridControl.UseCollectionEditor - Toggles collection editing for the entire property grid.
- CollectionDefinition.UseCollectionEditor - Toggles collection editing for individual collections.
<dxprg:CollectionDefinition UseCollectionEditor="True" >
The project includes the following examples:
- Collection - An example with a collection property.
- Dictionary - An example with a dictionary property.
Use the XamlInitializer class to allow users to add an item to a collection.
- Add the
XamlInitializer
class to theWindow.Resources
section.<Window.Resources> <dxprg:XamlInitializer Initialize="XamlInitializer_Initialize" x:Key="xamlInitializer" /> </Window.Resources>
- Specify a TypeDefinition and its attributes.
<dxprg:XamlInitializer Initialize="XamlInitializer_Initialize" x:Key="xamlInitializer"> <dxprg:TypeDefinition Type="{x:Type local:Supplier}" Name="Supplier" Description="New Supplier"/> </dxprg:XamlInitializer>
- In the XamlInitializer.Initialize event handler, initialize the new object's properties.
private void XamlInitializer_Initialize(object sender, InstanceInitializeEventArgs e) { e.Instance.FirstName = "FIRSTNAME"; e.Instance.LastName = "LASTNAME"; e.Instance.Phone = "PHONE"; }
Use Property attributes to allow users to add items to a dictionary.
In this example, the DictionaryKey1Attribute
class creates a unique key for a new item. Use this example as a template and create your own attribute class to generate unique keys.
- Add a
DictionaryKey1Attribute
class inherited from theDevExpress.Mvvm.DataAnnotations.NewItemInstanceInitializerAttribute
class.public class DictionaryKey1Attribute : NewItemInstanceInitializerAttribute { public DictionaryKey1Attribute() : base(typeof(Supplier)) { } public override KeyValuePair<object, object>? CreateInstance(ITypeDescriptorContext context, IEnumerable dictionary) { var testObject = ((DescriptorContext)context).Value as IDictionary<string, Supplier>; int key = testObject.Keys.Count; while(testObject.Keys.Contains(key.ToString())) key++; return new KeyValuePair<object, object>(key.ToString(), new Supplier()); } }
- Add the attribute to the dictionary property.
[DictionaryKey1()] public IDictionary<string, Supplier> Tags { get; set; } = new Dictionary<string, Supplier>();
Collections example:
- MainWindow.xaml (VB: MainWindow.xaml)
- MainWindow.xaml.cs (VB: MainWindow.xaml.vb)
- Products.cs (VB: Products.vb)
Dictionary example:
- MainWindow.xaml (VB: MainWindow.xaml)
- MainWindow.xaml.cs (VB: MainWindow.xaml.vb)
- Products.cs (VB: Products.vb)