Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValidationRules within control template

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)

like image 481
S Rosam Avatar asked Sep 05 '11 09:09

S Rosam


1 Answers

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.

like image 157
Natxo Avatar answered Sep 22 '22 15:09

Natxo