wpf 如何使用触发器制作文本框 Visibility=Hidden

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/631098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:06:35  来源:igfitidea点击:

How to make a text box Visibility=Hidden with a trigger

wpf.net-3.5stylesdatatrigger

提问by Russ

I seem to be having a hard time today. All I want to do is make a TextBoxhidden of visible based on a bool value databound to the Window its hosted in.

我今天好像过得很艰难。我想要做的就是TextBox根据绑定到其托管窗口的布尔值数据隐藏可见。

What I have just won't compile and I don't understand why. Please help.

我刚刚不会编译,我不明白为什么。请帮忙。

<TextBlock Grid.Column="2" Text="This order will be sent to accounting for approval" 
           Foreground="Red" VerticalAlignment="Center" FontWeight="Bold" Padding="5">
    <TextBlock.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=AllowedToSubmit}" Value="True">
                    <Setter Property="Visibility" Value="Hidden" /> 
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

回答by Robert Macnee

You need to set the Style.TargetTypein order for it to recognize the Visibilityproperty:

您需要设置Style.TargetType以使其识别该Visibility属性:

<TextBlock Grid.Column="2" VerticalAlignment="Center" FontWeight="Bold" Foreground="Red" Padding="5" Text="This order will be sent to accounting for approval">
    <TextBlock.Style>
        <Style TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=AllowedToSubmit}" Value="True">
                    <Setter Property="Visibility" Value="Hidden"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

Your binding path to AllowedToSubmitprobably needs to have ElementNameset to the Window's name, as well.

您的绑定路径 toAllowedToSubmit可能也需要ElementName设置为Window的名称。

回答by Andy

Another option is to bind TextBlock.Visibilitydirectly to the property:

另一种选择是TextBlock.Visibility直接绑定到属性:

<Window>
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVisibility" />
    </Window.Resources>
    <TextBlock Visibility="{Binding Path=AllowedToSubmit, Converter={StaticResource BoolToVisibility}}" />
</Window>

If you want it to work like in your sample, where true hides the TextBlock, then you can write your own converter to convert opposite of the built-in BooleanToVisibilityConverter.

如果您希望它像在您的示例中一样工作,其中 true 隐藏了TextBlock,那么您可以编写自己的转换器来转换内置的BooleanToVisibilityConverter.