Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextBlock trigger instead of using converter

I want to show a number on screen. If that number is 0 I don't want it to show at all.

<TextBlock Text="{Binding Path=Class.Count}" FontSize="20" FontWeight="Bold">
    <TextBlock.Triggers>
        <DataTrigger Binding="{Binding Path=Class.Count}" Value="0">
            <Setter Property="TextBlock.Text" Value=""/>
        </DataTrigger>
    </TextBlock.Triggers>
</TextBlock>

I attempted the above piece of code after a regular trigger failed to solve my problem. I do not want to write a converter to act upon one specific number. Is there a way to create a trigger that will hide the number if it is 0?

EDIT: When I try to use a regular trigger or a data trigger I get a xaml parse error telling me I need to use an event trigger.

I tried to set the value in the setter to a number to make sure that having a blank value was not causing the problem

like image 519
Joseph Devlin Avatar asked Jun 14 '11 14:06

Joseph Devlin


1 Answers

You are fighting with the binding to set the Text Property.

I'd make the control collapsed/hidden instead of setting the text to String.Empty.

Less confusion.

EDIT

<TextBox>
    <TextBox.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Name.Length}" Value="0">
                    <Setter Property="UIElement.Visibility" Value="Collapsed"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

OR

<TextBox>
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Name.Length}" Value="0">
                    <Setter Property="Visibility" Value="Collapsed"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
  1. Only a Style allows DataTriggers.
  2. The xaml parser wants to check the property's existence so it needs the ownertype. Visibility is declared on the UIElement class. There are two ways of specifying that as I have shown in both examples.
like image 148
Emond Avatar answered Nov 15 '22 11:11

Emond