0

I am working on a WPF application. And we have a number of "forms" within the application that have fields that require entry. I have read all about ValidationRules and I think I am grasping the concept well enough, but what I would like to do is build a CustomControl, or UserControl not sure which is more appropriate in this case, that has the ValidationRules baked right into it.

The end result of this being instead of saying

<ComboBox ItemsSource={Binding Items} />

I would say

<RequiredComboBox ItemsSource={Binding Items} />

I am just still a little to new to WPF to see where the right extension point to do this is.

LPL
  • 16,827
  • 6
  • 51
  • 95
Matt
  • 2,795
  • 2
  • 29
  • 47

1 Answers1

1

A ValidationRule belongs to a Binding. Thats why you would have to specify your Binding in your Control. If thats not a problem you could create a UserControl, instead of inheriting from ContentControl you inherit from ComboBox and in your XAML you do something like:

<ComboBox blabla
          local:xmlns="clr-namespace:YourNameSpace">
<ComboBox.ItemsSource>
     <Binding Path="Items">
          <Binding.ValidationRules>
               <local:YourValidationRule/>
          </Binding.ValidationRules> 
     </Binding>
</ComboBox.ItemsSource>
</ComboBox>

Another option for your would be to create your own Binding, which inherits from Binding and set its ValidationRule in the constructor like so:

public class ValidatedBinding:Binding
{
    public ValidatedBinding()
    {
        this.ValidationRules.Add(new YourValidationRule());
        this.ValidatesOnDataErrors = true;
    }
}

How to use it:

ItemsSource="{local:ValidatedBinding Path=Items}"/>
Florian Gl
  • 5,984
  • 2
  • 17
  • 30