3
votes

Don't know the term for the red validation border, does it have one?

I have a viewmodel that does not inherit from IDataErrorInfo. It binds an int property to a "quantity" textbox, so that when alpha characters are entered it gets a red validation border. This is perfect behavior. That red border is styled by the OS, so it fits. It doesn't require that I inherit from or implement IDataErrorInfo; it's simple and automatic.

Is there a way to get this same behavior for texbox's that are bound to strings, becoming red when the string are empty (or start empty). I know I could bind them to an object that inherits from IDataErrorInfo to do this, but I was wondering if a solution as simple as the one above exists.

I thought that the int binding on quantity threw an exception in the setter when you typed alpha characters. Doing the same in the setter of the string worked if you changed the value to empty, but it wasn't red if it started out empty (since the setter hasn't been called), and the setter caused visual studio to jump into the debugger first, which the quantity field doesn't do.

Is this possible, or is the int validation just a lucky exception?

Edit: HB's solution below works perfectly, unless you are working on an interface with a tabcontrol. See this SO question for a detailed explanation, but here is the short of it: validation errors are painted on a layer that is discarded when switching tabs. There is a simple solution to this, unless your validation error is raised on a control while it is on a tab that is not currently selected. Suddenly the solution becomes very complicated, and in my opinon, very hacky.

Edit: I have decided a datatrigger is probably the easiest way to handle this, and it is also easy to reuse.

<Style x:Key="TextBoxEmptyError" TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text.Length}" Value="0">
            <Setter Property="BorderBrush" Value="{StaticResource ResourceKey=SemiTransparentRedBrushKey}"/>
            <Setter Property="BorderThickness" Value="2" />
        </DataTrigger>
    </Style.Triggers>
</Style>
1
The red border is an instance of the ErrorTemplate no idea if there is a proper term besides that...H.B.

1 Answers

2
votes

You can add a ValidationRule to the Text-binding which gives an error on empty string input, to make it validate right away set ValidatesOnTargetUpdated to true.