Mar25
Initial expanded state of properties and PropertyGrid state saving/restoring
Once more, the idea of this article comes from a question I found on StackOverflow.
I would like to automatically expand some nodes in a PropertyGrid loaded with an instance of my SettingsStructure class by using attributes on the properties of that class. Also, I am attempting to have the instance 'remember' whether each property was expanded or not if the user loads that instance again on the PropertyGrid.
I was curious to see how easy/difficult it is to get this done in Smart PropertyGrid when using SelectedObject.
Here is a class to populate the grid:
public class TargetClass
{
[PropertyExpanded]
public Size Size { get; set; } = new Size(10, 20);
}
Initial expanded state for a property
This was really easy to set up an attribute to do that thanks to the new addition discussed in the previous blog post:
public class PropertyExpandedAttribute : PropertyCreatedHandlerAttribute
{
public override void OnPropertyCreated(PropertyEnumerator propEnum)
{
propEnum.Property.ParentGrid.ExpandProperty(propEnum, true);
}
}
And voilĂ , Size is expanded when SelectedObject is given an instance of TargetClass.
Save and restore the PropertyGrid state
Answering this question was instantaneous. Smart PropertyGrid already offers this feature. Here is an example taken from the online documentation:
var states = myGrid.SavePropertiesStates(PropertyStateFlags.None);
myGrid.SelectedObject = newTargetInstance;
// Then later
myGrid.BeginUpdate();
myGrid.SelectedObject = originalTargetInstance;
myGrid.RestorePropertiesStates(states);
myGrid.EndUpdate();
Note that SavePropertiesStates saves some states by default. The expanded state is one of them. First displayed and selected properties are some others. Passing PropertyStateFlags.None to this method does not mean that it must not save states at all. It means that it should not save more states (like colors and fonts) than the default ones.
The sample for this article has been added on github.