隐藏Canvas取决于孩子的内容

时间:2015-02-26 17:19:02

标签: wpf xaml datatrigger

这是我最近尝试在label.Content为空字符串时使画布不可见。任何帮助/建议表示赞赏,谢谢。

<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>

2 个答案:

答案 0 :(得分:1)

这里的问题是本地属性值的优先级始终高于Style Setter设置的值。请参阅Dependency Property Value Precedence

在“画布”上设置Visibility="Visible"时,将静默忽略该属性的任何样式设置器。您可以将属性分配移动到样式,但无论如何Visible是默认值:

<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>

请注意,现在有Value="{x:Null}"的第二个触发器。

答案 1 :(得分:0)

您需要将默认的Visibility属性移出<Canvas>标记并移至<Style>

这是因为<Tag>中定义的属性优先于任何属性设置器,包括触发的属性设置器。如果您需要更多详细信息,请参阅MSDN的Dependency Property Precedence List

<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>