Search code examples
wpfvalidationxamlexpander

How can I indicate in an Expander header that collapsed contents have an error


I have expanders that contain text boxes, the text boxes use the wpf validation stuff to draw a red box around them ( text boxes are wrapped in Adorner Decorators to make sure I don't get empty red boxes everywhere when the expanders are collapsed)

I want to indicate in the header of the expander that it has contents that have errors (in case it is in a collapsed state) - an icon or red exclamation mark or something. I think I see a way to do this in code from my validation function (not ideal) but is there a way to do it in xaml? Can I use a style for the expander with a trigger somehow pointing to the Validation.HasError of all children?

thanks for any thoughts..

Trev


Solution

  • If you know the contents of your expander, you can use a MultiDataTrigger to do this:

    <Expander>
        <Expander.Header>
            <TextBlock>
                <TextBlock.Style>
                    <Style TargetType="{x:Type TextBlock}">
                        <Setter Property="Text" Value="ERROR"/>
                        <Style.Triggers>
                            <MultiDataTrigger>
                                <MultiDataTrigger.Conditions>
                                    <Condition Binding="{Binding ElementName=txtWidth, Path=(Validation.HasError)}" Value="False"/>
                                    <Condition Binding="{Binding ElementName=txtHeight, Path=(Validation.HasError)}" Value="False"/>
                                </MultiDataTrigger.Conditions>
                                <Setter Property="Text" Value="NO ERROR"/>
                            </MultiDataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
        </Expander.Header>
        <StackPanel>
            <TextBox x:Name="txtWidth" Text="{Binding Width, ElementName=rect, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}"/>
            <TextBox x:Name="txtHeight" Text="{Binding Height, ElementName=rect, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}"/>
            <Rectangle x:Name="rect" Width="100" Height="100" Margin="10" Fill="Green"/>
        </StackPanel>
    </Expander>
    

    If the contents of the expander aren't known, then you'll probably have to set Binding.NotifyOnValidationError on the TextBoxes and handle the Error attached event.