Ramblings of a .NET Developer

1 December 2012

Saturday, December 01, 2012 | by Paul | Categories: , | No comments
I've been programming with WPF now since it was in beta. But it only recently dawned on me that I can circumvent the annoying binding code you have to put into TextBoxes.

Currently, we have to do something like this to have our data bind with validation and update the model immediately.



<TextBox Text="{Binding Path=TextValue, UpdateSourceTrigger=PropertyChanged, 
    ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" /> 
 
Pretty standard stuff. But I'd rather do this and have it work the same.
<TextBox Text="{Binding Path=TextValue}" /> 
 

So how can we do this?

It turns out, quite easily. All we have to do is default some properties on a custom binding.
 
First create a WPF Custom Control Library and call it WPFToolBox.
Add a new class called BindingExtension.cs and add the following code.
 
    /// <summary>
    /// By default, sets the binding to validate and update on PropertyChanged
    /// </summary>
    public class BindingExtension : Binding
    {
        public BindingExtension()
        {
            Init();
        }
 
        public BindingExtension(string path)
        {
            Init();
            Path = new PropertyPath(path);
        }
 
        public BindingExtension(object source, string path)
        {
            Init();
            Source = source;
            Path = new PropertyPath(path);
        }
 
        private void Init()
        {
            NotifyOnValidationError = true;
            ValidatesOnDataErrors = true;
            ValidatesOnExceptions = true;
 
            UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        }
    }
 
One more step before it's ready to go.
Open the AssemblyInfo.cs file under Properties, and add the following namespace definition
[assemblyXmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation""WPFToolBox")] 
 
This definition adds the namespace of our project to the presentation xml namespace.
It will allow any classes in that namespace to be available to the user through the global XAML definition.
The Binding automatically picks up our custom binding class instead of the version in System.Windows.Data. 
 
That's it! Now build the project, reference it from your main app and your ready to write nice clean XAML!