I have a WPF screen that displays a number of TextBox inputs. I have a style that handles all the validation:
<Style x:Key="TextBoxStyle" BasedOn="{x:Null}" TargetType="{x:Type TextBox}">
<!-- etc etc -->
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<Border Grid.Column="0" BorderBrush="Red" BorderThickness="1">
<StackPanel>
<AdornedElementPlaceholder />
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
The only thing I have to apply to the TextBox is to tell the binding that it validates. Seeing as I have quite a number of these boxes over the application, I would prefer not to repeat this ad nauseum for the entire application.
<TextBox Text="{Binding TargetValue, ValidatesOnExceptions=true, ValidatesOnDataErrors=true, NotifyOnValidationError=true}" Style="{DynamicResource TextBoxStyle}" />
I've tried adding the Text.Binding.ValidatesOnDataErrors property to the style, which doesn't work nor seem like the correct way to do it. Is it possible t开发者_开发问答o create a default binding style? Any suggestions appreciated!
Unfortunately, there's no way of overriding the default values for Binding properties. An alternative approach you could take is to create your own custom Binding extension with ValidatesOnException and ValidatesOnDataError both set to true. In this way, you can do something like:
<TextBox Text="{BindingWithValidation TargetValue}/>
You can use the base class provided in this article to make it a bit easier to create your custom binding markup extension.
精彩评论