I started a hobby project to learn about WPF and in my reasearch i stumpled upon this WPF PropertyGrid http://www.codeplex.com/wpg
I downloaded the source from http://wpg.codeplex.com/SourceControl/ListDownloadableCommits.aspx
, And started browsing through it, looks cool, and works. But for the life of me, I can’t figure out HOW it works. The following questions is what I’m left with at first glance.
- How does it know what properties an object have?
- How does it render the control to edit a Value?
- How does it decide what control to render? (i’m guessing meta data descriptions on the properties)
I understand the DependancyProperties handles the dataexchange between new values.
- Where is the XAML or CodeBehind code that does all the magic?
There is lots of XAML code in the Default.xaml file, but as far as I can tell it is only styles and the looks that are defined there.
It uses
System.ComponentModel.TypeDescriptorto determine the properties that a type has viaTypeDescriptor.GetProperties. APropertyDescriptorprovides a wealth of information about each property (e.g.,PropertyDescriptor.IsReadOnlywill tell you that a property is readonly). Further, usingPropertyDescriptor.GetValueandPropertyDescriptor.SetValue, the values of properties can be obtained and written to.It uses a custom control called a
PropertyGridwhich exposes anObservableCollectionofItems.Itemis merely a base class for the core model object which isProperty.Propertyexposes the underlying type (PropertyDescritor.PropertyType) of the property and exposes thePropertyDescriptor.GetValueandPropertyDescriptor.SetValuemethods viaProperty.Value. This, in turn, is what is bound to to enable the editing.DataTemplates are the key here. A few CLR types have customDataTemplates that render the controls you see. For example, theBooleantype is rendered as aCheckBoxwhile anEnumis rendered as aComboBox. The defaultDataTemplateis aTextBox.The propensity of it is in
Themes\Default.xaml.The code can be summarized as thus. There is data (
Data\Property) that encapsulates the information about properties of an object and provides a property (Property.Value) to read and write the value of a property. This data is exposed as anObservableCollectionin a custom control (PropertyGrid) which is rendered usingDataTemplates inThemes\Default.xaml.Don’t overlook the
DataTemplates.