For the visuals in our WPF project we use the WPF toolkit. An awesome library that offers a lot of controls for free (Community Edition) and even more controls in the paid editions.
When editing a string property in the PropertyGrid, we noticed some strange behaviour. The ViewModel would only be updated after changing the selection. This required the user to first switch to another property before clicking the save button. Unacceptable!
Custom Editors with DataTemplates in the WPF Toolkit documentation handed the solution. But first we dug around the source code for the controls. Why was the string property not updated as we typed the new value?
A string in the PropertyGrid is default edited with the PropertyGridEditorTextBox control. This can be stripped down to a TextBox. The TextBox has UpdateSourceTrigger set to LostFocus. All other types (int, DateTime, bool) have default controls that handle the change of value like masters, so no coding required for those.
We made a custom editor for strings and hooked it up to the PropertyGrid by adding the EditorAttribute to the ViewModel. See simplified code below.
public class InstantUpdatingTextBox : ITypeEditor{ public FrameworkElement ResolveEditor(PropertyItem propertyItem) { var textBox = new TextBox(); var _binding = new Binding("Value"); _binding.Source = propertyItem; _binding.ValidatesOnExceptions = true; _binding.ValidatesOnDataErrors = true; _binding.Mode = BindingMode.TwoWay; _binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; BindingOperations.SetBinding(textBox, TextBox.TextProperty, _binding); return textBox; } } public class ViewModel { [Category("(General)")] [Editor(typeof(InstantUpdatingTextBox), typeof(InstantUpdatingTextBox))] public string Name { get { return _name; } set { _name = value; RaisePropertyChanged(() => Name); } } }
Now we see changes everywhere as we type the new value. Got to love WPF and its DataBinding. 😉
Pingback: WPF Toolkit DateTimePicker customisation of header | .NET Development by Eric