I have control thats inherits from textbox
public class MyTextBox : TextBox
This has a style
<Style TargetType="{x:Type Controls:MyTextBox}">
one of the Setters is
<Setter Property="Template">
I want to be able to set the Binding.ValidationRules
to something in the template, thus affecting all instances of this type of textbox.
I can therefore make textboxes for say Times, Dates, Numerics, post/zip codes.. or whatever i want,
I don't want to have to set the validation rules every time i create a textbox. I just want to say i want a NumericTextBox
and have it validate in whatever way is set in the template.
Is this possible?
All i have seen so far is the ValidationRules being set on each instance of the control e.g.
<TextBox x:Name="txtEMail" Template={StaticResource TextBoxErrorTemplate}>
<TextBox.Text>
<Binding Path="EMail" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<local:RegexValidationRule Pattern="{StaticResource emailRegex}"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
(from http://www.wpftutorial.net/DataValidation.html)
As you see, validation rules are set along with bindings. I came across the same problem and the working solution for me was to do something like this:
public MyTextBox()
{
this.Loaded += new RoutedEventHandler(MyTextBox_Loaded);
}
void MyTextBox_Loaded(object sender, RoutedEventArgs e)
{
var binding = BindingOperations.GetBinding(this, TextBox.ValueProperty);
binding.ValidationRules.Add(new MyValidationRule());
}
The problem here is to be sure that the binding is set before we add the validation rule, hence the use of Loaded, but i'm not sure if this will work on every scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With