Search code examples
wpfdata-bindingvalidationerror

Representing a validation error within a control that is not of the data-bound control?


I have a TextBlock within a DockPanel within a Border. The TextBlock is data-bound and can be changed with an on-screen keyboard. Therefore, I have hooked it up to validation and it works wonderfully. My dilemma is that I can only seem to change the TextBlock's style when there is a validation error. I want to trigger the Border's style. How can I do this?

Also is there a way to bind the ErrorContents elsewhere on the view?


Solution

  • Just bind to your TextBox from some other control. Below I bound a Label's Content property to a TextBox's (Validation.Errors)[0].ErrorContent property.

    <DockPanel>
    
        <!-- TextBox bound to a data object-->
        <TextBox Name="textBox1" DockPanel.Dock="Top" Text="{Binding Path=Age, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"></TextBox>
    
        <!-- A label that displays the errors from textBox1 -->
        <Label Content="{Binding ElementName=textBox1, Path=(Validation.Errors)[0].ErrorContent}"></Label>
    
    </DockPanel>