Property grids are great for quickly giving users an interface for interacting with objects in WPF but customising them is not obvious. Luckily it is possible by extending the UIEditor class to launch custom GUI controls.
In this example I wanted to customise the default DateTime handler of PropertyGrid to include hours, minutes and seconds as unfortunately it only shows the date by default. The following class shows how to extend UIEditor in order to launch a pop-up DateTimePicker when the user selects the item.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using System; using System.ComponentModel; using System.Drawing.Design; using System.Windows.Forms; using System.Windows.Forms.Design; namespace Util { public class DateTimePickerEditor : UITypeEditor { IWindowsFormsEditorService editorService; DateTimePicker picker = new DateTimePicker(); public DateTimePickerEditor() { picker.Format = DateTimePickerFormat.Custom; picker.CustomFormat = "dd/MM/yyyy HH:mm:ss"; } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if (provider != null) { this.editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; } if (this.editorService != null) { picker.Value = value; this.editorService.DropDownControl(picker); value = picker.Value; } return value; } } } |
Then in order to add that to your property grid, add the following to the DateTime item in the class used by the PropertyGrid –
1 2 3 4 5 6 |
[DisplayName("Start Time"), EditorAttribute(typeof(DateTimePickerEditor), typeof(UITypeEditor))] public DateTime StartTime { get { return startTime; } set { startTime = value; } } |
The key part here is the EditorAttribute.
Update
Here’s a great article explaining custom UITypeEditors in more detail – http://bobpowell.net/TypeEditors.aspx
July 2, 2014 at 1:34 pm
Can u please share your code here…
I did the same but nothing is happening. Also putting the break points at the constructor doesn’t hit.