tags:

views:

489

answers:

2

How would I create a validation rule to ensure Value2 has the same value as Value1? If a validation rule is not the best method then what would be better? I could have the TextChanged event handle this, but I'm wondering if there is something more elegant.

<TextBox Name="Value1TextBox">
    <TextBox.Text>
        <BindingPath Path="Value1" UpdateSourceTrigger="PropertyChanged" />
    </TextBox.Text>
</TextBox>

<TextBox Name="Value2TextBox">
    <TextBox.Text>
        <BindingPath Path="Value2" UpdateSourceTrigger="PropertyChanged" />
    </TextBox.Text>
</TextBox>
+1  A: 

Looks like implementing the System.ComponentModel.IDataErrorInfo interface and adding ValidatesOnDataErrors did the trick.

<TextBox Name="Value2TextBox">    
    <TextBox.Text>        
        <BindingPath Path="Value2" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" />
    </TextBox.Text>
</TextBox>
Taylor Leese
+1  A: 

Validation rules are not too handy, if you need to combine multiple values for your validation. If you have access to the bound datatype, then implementing IDataErrorInfo there will be much easier, and you only need to enable validation on your Binding with ValidateOnDataError=True. If not, you will need to do some work to parametrize your ValidationRule: Either use this workaround Virtual branch pattern by Josh Smith or some binding-proxy as described here (very nice helper, by the way) Binding Proxy by Douglas Stockwell

With one of those you should manage to make one binding be a parameter for your validation rule, when validating the other one.

Simpzon
Seems strange to me that it's so involved to pass a dynamic value to a validation rule. It makes me think I'm missing something.
Taylor Leese
The crucial about it is that the validation rule is a resource, not part of the visual tree, so you can't bind anything to it directly.Of course there are also easy ways: if you are not searching for the perfect architecture, you could just bind from the textboxes to some static property and then access this static property from within the validation rule.
Simpzon