In previous articles we discussed How to use a PropertyGrid to create a settings interface and we talked about Editable DataGrid and ObservableDictionary. Now we are going to make use of both of those concepts and create a DataGridEditor
to be used in a PropertyGrid of the Extended WPF Toolkit.
Making a DataGridEditor
You have several ways of making a custom editor for a PropertyGrid. In this case we will be implementing the ITypeEditor
interface.
public class DataGridEditor : ITypeEditor
{
public FrameworkElement ResolveEditor(PropertyItem propertyItem)
{
var grid = new DataGrid();
grid.MaxHeight = 400;
var button = new DropDownButton();
button.Content = "(Collection)";
button.DropDownContent = grid;
button.IsTabStop = true;
button.MinHeight = 22;
button.SnapsToDevicePixels = true;
button.Background = Brushes.White;
button.BorderThickness = new Thickness(0);
button.Padding = new Thickness(2, 0, 0, 0);
button.HorizontalAlignment = HorizontalAlignment.Left;
button.VerticalAlignment = VerticalAlignment.Center;
var _binding = new Binding("Value");
_binding.Source = propertyItem;
_binding.ValidatesOnExceptions = true;
_binding.ValidatesOnDataErrors = true;
_binding.Mode = propertyItem.IsReadOnly ? BindingMode.OneWay : BindingMode.TwoWay;
BindingOperations.SetBinding(button.DropDownContent as DataGrid, DataGrid.ItemsSourceProperty, _binding);
return button;
}
}
Pretty straightforward. We just create a DataGrid and place it as the content of a DropDownButton. I customized the properties to my liking.
Define the editor for the property
You can specify the editor by using an attribute on the property.
[Category("General settings")]
[DisplayName("Countries")]
[Editor(typeof(DataGridEditor), typeof(DataGridEditor))]
public ObservablePairCollection<string, string> Countries { get; set; }
Final result
Using a DataGrid in a PropertyGrid: