hide Canvas depending on child's content

2019-09-10 07:52发布

问题:

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>

回答1:

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.



回答2:

You need to move the default Visibility property out of the <Canvas> tag and into the <Style>

This is because properties defined in the <Tag> take precedence over any property setters, including triggered property setters. See MSDN's Dependency Property Precedence List if you want more details.

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