Reputation: 305
I want to make WPF validations run only if the control that is being validated is Visible.
In my project, depending on the user's choice, some controls are Collapsed.
I have a button that is enabled only if there are no validation errors (I use WPF MultiValue Converter and check if all controls are valid - HasError is false for all controls).
Validations are implemented using ValidationRules.
So, my goal is to validate all currently Visible controls (Only Visible!), instead of Button being disabled because collapsed fields are empty...
Is there a way to make Validation Error raise only when control is Visible and input is Invalid?
I have searched on the internet for a few days, but I haven't found any solutions for this situation...
Thanks in advance! Best regards!
Upvotes: 0
Views: 1538
Reputation: 966
You can add property to your validation rule like Enabled and use it while validating (return successfull validation if not enabled). Then bind that property in XAML to either Visibility property of the control or whatever determines if control is visible (ie. CheckBox's IsChecked property). Edit: Code for clarity:
<CheckBox Name="chkName" />
<TextBox Visibility="{Binding IsChecked, ElementName=chkName, Convertor...}">
<TextBox.Text>
<Binding Path="ModelProperty">
<Binding.ValidationRules>
<wpfApp1:TextValidationRule Enabled="{Binding IsChecked, ElementName=chkName}" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Upvotes: 1
Reputation: 1046
If you use xaml for setting your rules the code below do what yuo want. Trigger for visibility, no binding - no validation) I used TextBox only as example. Also you can use other approach, pass to your ValidationRule your property which shows that elements are hidden, and check it inside rules How to bind values from xaml to validation rule?
<TextBox Visibility="{Binding IsVisible, Converter={wpfApp1:BoolToVisibilityConverter}}">
<TextBox.Text>
<Binding Path="Text" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<wpfApp1:TextValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Visibility" Value="Collapsed">
<Setter Property="Text" Value="{x:Null}"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
Upvotes: 1