hide Canvas depending on child's content

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 06:04:21

问题


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>


来源:https://stackoverflow.com/questions/28748734/hide-canvas-depending-on-childs-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!