Category / Section
How to Get the Parent Property of the Nested Items in the PropertyGrid
3 mins read
This article explains how to obtain the parent of a nested property in the PropertyGrid by utilizing reflections to access the internal property ParentPropertyItem and leveraging its Name property to retrieve the corresponding ParentPropertyItem object.
Step 1: Create the Model classes.
C#
public class Address
{
public string State { get; set; }
public string StreetName { get; set; }
public string DoorNo { get; set; }
public override string ToString()
{
return DoorNo + ", " + StreetName + ", " + State;
}
}
public class AddressDetails
{
public Address Address1 { get; set; }
public Address Address2 { get; set; }
}
Step 2: Create the ViewModel class.
C#
public class ViewModel
{
public object SelectedAddress { get; set; }
public ViewModel()
{
SelectedAddress = new AddressDetails()
{
Address1 = new Address()
{
State = "New York",
DoorNo = "10",
StreetName = "Martin street"
},
Address2 = new Address()
{
State = "United States",
DoorNo = "15",
StreetName = "Main street"
}
};
}
}
Step 3: Create a ValueChanged event for the PropertyGrid control.
XAML
<!--Initializes the PropertyGrid Control-->.
<syncfusion:PropertyGrid PropertyExpandMode="NestedMode" SelectedObject="{Binding SelectedAddress}" ValueChanged="propertyGrid_ValueChanged" x:Name="propertyGrid" >
<syncfusion:PropertyGrid.DataContext>
<local:ViewModel></local:ViewModel>
</syncfusion:PropertyGrid.DataContext>
</syncfusion:PropertyGrid>
Step 4: To obtain the parent of the nested PropertyItem, iterate through the list and check if the name of the parent property matches the desired property name. By doing so, you will be able to retrieve the parent of the nested PropertyItem.
C#
private void PropertyGrid_ValueChanged(object sender, ValueChangedEventArgs args)
{
// Obtain the PropertyInfo of all properties within the using reflection.
PropertyItem propertyItem= args.PropertyItem;
Type objectType = propertyItem.GetType();
// Get all properties of the PropertyItem type using reflection.
PropertyInfo[] properties = objectType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach(PropertyInfo property in properties)
{
if(property.Name == "ParentPropertyItem")
{
PropertyInfo parentPropertyItem = property;
object propertyValue = parentPropertyItem.GetValue(propertyItem);
string propertyName;
if (propertyValue != null)
{
PropertyItem propertyItem1 = (PropertyItem)propertyValue;
propertyName = propertyItem1.Name;
}
break;
}
}
}
Output:
Figure:1 Parent property of the Nested Item