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

Russ picture Russ · Mar 10, 2009 · Viewed 31k times · Source

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>

Answer

Robert Macnee picture Robert Macnee · Mar 10, 2009

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.