Home > database >  How to change a parent by validating a child?
How to change a parent by validating a child?

Time:02-09

I have a DockPanel that is composed of a button and a textbox. These controls are enclosed by a border. Now I would like to validate the textbox and change the color of the border if the validation fails.

However, in my current application, the validation only affects the textbox itself.

<Border>
    <DockPanel>
        <Button Command="{Binding GetFolder}">
            <Button.Template>
                <ControlTemplate>
                    <Image Source="/Assets/Icons/Folder.png"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
        <TextBox 
            Text="{Binding 
            Path=DataFolder, 
            ValidatesOnDataErrors=True,
            Mode=TwoWay, 
            UpdateSourceTrigger=PropertyChanged, 
            NotifyOnSourceUpdated=True}">
        </TextBox>
    </DockPanel>
</Border>

I know that I can give the Border an ErrorTemplate:

<Border Validation.ErrorTemplate="{StaticResource errorTemplate}">...,

But how do I tell it the result of the validation of the textbox?

CodePudding user response:

You could use a Style with a DataTrigger that binds to the attached Validation.HasError property of the TextBox:

<Border>
    <Border.Style>
        <Style TargetType="Border">
            <Style.Triggers>
                <DataTrigger Binding="{Binding (Validation.HasError),ElementName=tb}"
                             Value="True">
                    <Setter Property="BorderThickness" Value="1" />
                    <Setter Property="BorderBrush" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
    <DockPanel>
        <Button Command="{Binding GetFolder}">
            <Button.Template>
                <ControlTemplate>
                    <Image Source="/Assets/Icons/Folder.png"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
        <TextBox x:Name="tb"
                    Text="{Binding 
                    Path=DataFolder, 
                    ValidatesOnDataErrors=True,
                    Mode=TwoWay, 
                    UpdateSourceTrigger=PropertyChanged, 
                    NotifyOnSourceUpdated=True}">
        </TextBox>
    </DockPanel>
</Border>
  •  Tags:  
  • Related