Thursday, December 17, 2015

Setting the Background of a WPF TextBox depending on Validation in a Template/Style using TemplateBinding 2


I showed how to change the Background of a TextBox, if some own ValidationRule failed in the post Setting the Background of a WPF TextBox depending on Validation in a Template/Style using TemplateBinding. But the solution has a minor issue.

If the VisualState is ReadOnly and the Trigger Validation.HasError is called the Background changes as expected. But if the Trigger is not any longer true, the Background will not set back to the ReadOnly style, again.

To fix this issue the VisualState of ReadOnly is removed.

                                <VisualState x:Name="ReadOnly" />

And a Trigger for the IsReadOnly property is defined. This Trigger must be placed above the Validation.HasError Trigger. Otherwise the TextBox would have always the ReadOnly color and never the HasError color.

        <Style.Triggers>
            <Trigger Property="IsReadOnly"
                     Value="True">
                <Setter Property="Background"
                        Value="LightBlue" />
            </Trigger>
            <Trigger Property="Validation.HasError"
                     Value="True">
                <Setter Property="ToolTip"
                        Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                                        Path=(Validation.Errors).CurrentItem.ErrorContent}" />
                <Setter Property="Background"
                        Value="Orange" />
                <Setter Property="BorderThickness"
                        Value="2" />
                <Setter Property="BorderBrush"
                        Value="Red" />
            </Trigger>
        </Style.Triggers>