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

风流意气都作罢 提交于 2019-12-20 10:38:04

问题


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

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>

回答1:


You need to set the Style.TargetType in order for it to recognize the Visibility property:

<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 AllowedToSubmit probably needs to have ElementName set to the Window's name, as well.




回答2:


Another option is to bind TextBlock.Visibility directly to the property:

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



来源:https://stackoverflow.com/questions/631098/how-to-make-a-text-box-visibility-hidden-with-a-trigger

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