Saturday, September 29, 2012

Dynamically Generated Properties using CustomTypeDescriptor for WPF Binding

In the previous post we discussed how we can use DynamicObject to add dynamically generated properties to our types. This post would continue the discussion but here we are going to discuss ICustomTypeDescriptor to add dynamically generated properties. We will also discuss how we can use these properties for WPF Binding. In the last part of our discussion we will be adding the missing bit to support change notifications for these properties.

System.ComponentModel has a default implementation of ICustomTypeDescriptor. This provides the interface implementation requirements in the form of virtual methods which can be overridden in your custom type. We will be using this implementation as part of our discussion. Basically the following methods from the interface do all the magic. We can provide implementation of these methods to introduce our custom properties in order to fake the client that the type already has these properties.


This is also more to do with WPF Binding System. If the DataContext implements ICustomTypeDescriptor then WPF Binding system uses the Type Descriptor instead of relying on reflection. From msdn, this discussion is very useful to learn how binding references are resolved.

http://msdn.microsoft.com/en-us/library/bb613546.aspx

Both of the overloads of GetProperties() methods return PropertyDescriptorCollection. It is a collection of PropertyDescriptor. Overriding these methods and adding further items to the collection can give the impression to the WPF Binding system of having these properties by the type itself. Let's provide a descriptor inheriting from PropertyDescriptor.

In the above property descriptor, please look at GetValue and SetValue methods. The type is holding a field called propertyValue. These methods operate on this field. We don't need these methods for working with WPF Binding system and need them to work with the additional properties in our code. Let's use this descriptor to create a Type implementing ICustomTypeDescriptor. We are maintaining an internal collection _myProperties to hold the additional properties which are not provided by the type itself. This would create perception of dynamically generated properties. An additional method, called AddProperty, is provided to add an item to the collection. The method is generic to support a property with any supported type. The type is also implementing INotifyPropertyChanged interface providing change propagation support. This would raise familiar PropertyChanged event when a value is changed using SetValue method.

Now let's use this type and introduce a new type called StudentViewModel. It maintains a property called FirstName. Now here is the intersting part. We are adding another property LastName using AddProperty method of the base type ViewModelBase.

Similarly, we add a new type called MainViewModel. Here also we are adding a property called MainTitle. We are setting the value of this property as "Main App Window". It is maintaining a collection holding a collection of StudentViewModel. Here we are adding members to the collection. We are setting the property of FirstName directly. We are setting the other property LastName using SetPropertyValue method. Another property SelectedStudent is provided to hold the currently selected student.

Now let's use these view models for WPF Binding. We are using MainViewModel as the DataContext of MainWindow. The view mainly has a ListBox and DataGrid to show items from Students collection in the DataContext. There is no difference in the use of FirstName and LastName properties from StudentViewModel even when LastName is being dynamically generated. You can also notice MainTitle being used for App banner.

Since the basic setup is done. Now let's run the application now. We should see the following display:


Supporting Change Notifications
This looks perfect but this has one limitation. This doesn't support change notifications for newly added properties. Since we are using PropertyDescritptor to add dynamic properties, we can easily add this behavior using OnValueChanged from the type. We first need to update the ViewModelBase so that whenever a property is added, we add the ValueChanged to the property descriptor and call OnPropertyChanged from ViewModelBase similary to the existing properties from the inheriting types.

Next we need to add the support in the inheriting PropertyDesriptor type i.e. CustomPropertyDescriptor. This would cause the ValueChanged to be used when SetValue method is called. In turn, PropertyChanged from ViewModelBase would be raised for the same property.


Download


5 comments:

Anonymous said...

Muhammad, thanks for the provided solution. It's amazing.
Now I try to apply it to my WPF PropertyGrid.
Right now, all Students share the same properties. Could you show how to implement properties that are specific for each model object. E.g. the first Student (Muhammad) has different number of properties than the second (Koi).

Muhammad Shujaat Siddiqi said...

Hi Koi,

Glad to help! Basically this solution is just for that purpose when properties are defined on type level. For instance specific properties, I would rather add a key / value pair collection to the type.

Koi said...

The thing is that I have mixed properties: type specific and instance specific. How could I merge a key-value Dictionary of with your solution. I found a good way to bind a Dictionary: http://stackoverflow.com/questions/3669660/can-propertygrid-edit-any-old-list-of-key-value-pairs
But as I said, it's a total different approach to yours and I don't know how to merge it. I like your linq style, so I would prefer yours as base ;-)

કૃણાલ said...

Hi,
You have in response to Koi's question mentioned that this particular solution is to define the properties at type level and not instance level. But I think it is not the case.

In your example, you need to make a call for "AddProperty" either on each instance object or somewhere in the class definition in order to add particular property to that instance object. Both these defeats the purpose of adding properties dynamically.

Ideally, "AddProperty" method should be static property so that no need to make "AddProperty" call on each instance object in order to add the dynamic property. Do you see the possibility of making "AddProperty" static?

Andrey Stepanov said...

Hello, you said that it also works for dynamic properties, i thought you meant DynamicObject, but our class already inherited from your base class, how to make it truly dynamic?
I see 2 ways:
1) Implement Methods of ICustomTypeDescriptor directly in class (but here i have some problems , for example i dont know hwere _parent might come from and how to use it correctly)
2) Use AddProperty method to add properties on runtime with values. But when i do that somehow all my values shown the same for all objects in collection.
Do you have any thoughts on that? Thank you