Getting Started

Editing an Object – the SelectedObject Property

The basic scenario for the WPF Property Grid is to edit a single object. This usage is similar to the Windows Forms PropertyGrid control.

CopyAttaching the Person object
1TestGrid.SelectedObject = Person.Alice;

Run the application and edit the properties.

Adding Custom Entries – the AddNode Methods

You can also add custom entries to the WPF Property Grid. You supply a name and an initial value. The user can then edit that value. When you need to, you can retrieve the value. You can build a grid entirely out of custom entries, or you can use custom entries to supplement an object’s real properties.

CopyNode list declaration
1private readonly List<Node> _addedNodes = new List<Node>();

CopyAdding values to the grid
1string caption = "Item " + (_addedNodes.Count + 1).ToString();
2string value = caption;
3Node addedNode = TestGrid.AddNode(caption, value);
4_addedNodes.Add(addedNode);

CopyDisplaying node values
1StringBuilder sb = new StringBuilder();
2foreach (Node node in _addedNodes)
3{
4  sb.AppendFormat("{0} = {1}", node.HumanName, node.Value);
5  sb.AppendLine();
6}
7MessageBox.Show(sb.ToString(), "Node Values");

Run the application and click the AddNodeCmd button a few times. Edit the values of the newly created nodes, and click the ViewNodesCmd button to see that the edited values have been retrieved from the grid.

Editing a Bound Collection – the ItemsSource Property

Instead of adding entries through code, you can also specify a collection as the source of the property grid data by using the ItemsSource property. This overrides the SelectedObject property and any manually added nodes. The ItemsSource must be a dictionary – that is, it must implement the IDictionary interface. The property grid displays the dictionary keys as the “property names” (captions).

CopyInitialising sample data
1_itemsSource.Add("a", "indefinite article, doesn't really mean anything");
2_itemsSource.Add("aardvark", "medium-sized insectivore with protruding nasal implement");
3_itemsSource.Add("bee", "a buzzing thing");
4_itemsSource.Add("sea", "big blue wobbly thing that mermaids live in");
5_itemsSource.Add("alice", Person.Alice);

CopyUsing the dictionary as the grid ItemsSource
1TestGrid.ItemsSource = _itemsSource;

Run the application, choose the BindToDictionaryCmd button and note that the existing entries are replaced by the dictionary entries. You can now edit the dictionary entries.

Use the ObservableDictionary class to have the PropertyGrid automatically reflect changes in the underlying dictionary.