开发者

ValidationRules within control template

开发者 https://www.devze.com 2023-04-03 05:09 出处:网络
I have control thats inherits from textbox public class MyTextBox : TextBox This has a style <Style TargetType=\"{x:Type Controls:MyTextBox}\">

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 inst开发者_开发技巧ances 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.


I am not sure it is possible to do exactly what you want. You might be able to do it with a lot of trickery in property setters (I wouldn't rely on this, since it would involve modifying bindings, which are by definition dynamic), or with code behind/custom controls.

Instead I suggest you push your validation into your ViewModel, probably with IDataErrorInfo. There are many articles out there. Here's one of the first ones I found with a search just now for "MVVM validation":

MVVM - Validation

Doing this will allow you to use standard OO composition techniques, so you can avoid repeating yourself :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号