views:

29

answers:

1

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 to create a default binding style? Any suggestions appreciated!

+2  A: 

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.

karmicpuppet
I don't think I'll go to all that trouble, but it seems sound. There's Don't Repeat Yourself and there's Don't Be Ridiculous. :)
rrhartjr
Indeed. Good for you. =)
karmicpuppet