Binding a C# property to a WPF validated Control
The DataBinding in WPF allows the binding of control properties to many things, like other control properties, arrays, data providers, ... But it can also bind a control property to a property defined by code on the C# side.
It is interesting to bind to C# property to be able to have the integrated WPF validation and still use a simple property from the code. In that case, I wanted to have the validation of a TextBox displaying a DateTime object.
Here's how to do this.
On the C# side :
[code:c#]
public partial class Window1 : Window
{
public Window1()
{
MyDate = DateTime.Now;
InitializeComponent();
}
public DateTime MyDate { get; set; }
}
[/code]
Note that I'm using the latest C# 3.0 syntax to declare variable-less properties. This is compiler trick, the variable is still declared at compile time, but since I don't need to have a specific code in the get or set accessor, it can stay in this short form.
Now on the XAML side :
[code:xml]<Window ... >
<TextBox Width="100" Height="20">
<Binding Path="MyDate" RelativeSource="{RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox>
</Window>
[/code]
The interesting part here is the use of RelativeSource and the FindAncestor mode. Here, we're looking for the property MyDate from the nearest ancestor instance of the Window type, from the current instance.
This way, you'll have a validated date time in your property value. Just make sure you're checking that the value is really valid using the System.Windows.Controls.Validation class.