Search code examples
wpfxamldatatrigger

hide Canvas depending on child's content


this is my latest try to make the canvas Invisible whenever the label.Content is an empty String. Any help/advice appreciated, thanks.

<Canvas Visibility="Visible">
    <Label Content="" Name="holamouse" />
    <Canvas.Resources>
        <Style TargetType="{x:Type Canvas}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Content, ElementName=holamouse, UpdateSourceTrigger=PropertyChanged}" Value="{x:Static sys:String.Empty}">
                    <Setter Property="Canvas.Visibility" Value="Hidden"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Canvas.Resources>
</Canvas>

Solution

  • The problem here is that a local property value always has higher precedence than a value set by a Style Setter. See Dependency Property Value Precedence.

    When you set Visibility="Visible" on the Canvas, any Style Setter for that property is silently ignored. You could move the property assignment to the Style, although Visible is the default value anyway:

    <Canvas>
        <Label Content="" Name="holamouse" />
        <Canvas.Resources>
            <Style TargetType="{x:Type Canvas}">
                <Setter Property="Visibility" Value="Visible"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Content, ElementName=holamouse}"
                                 Value="{x:Static sys:String.Empty}">
                        <Setter Property="Visibility" Value="Hidden"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Content, ElementName=holamouse}"
                                 Value="{x:Null}">
                        <Setter Property="Visibility" Value="Hidden"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Canvas.Resources>
    </Canvas>
    

    Please note also that there is a second trigger for Value="{x:Null}" now.