TextBlock trigger instead of using converter
Asked Answered
P

1

5

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

Pipage answered 14/6, 2011 at 14:14 Comment(0)
H
8

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.
Hamartia answered 14/6, 2011 at 14:26 Comment(3)
Already thought of that but there is no visibility property on the TextBlock. I could encapsulate the TextBlock inside another control that does etc but I am trying to avoid any complexity for something I view as so simple.Pipage
I wrote the exact same thing but had 'FrameworkElement.Visibility' instead of 'Control.Visibility' and I did not use a style. Once I added the style to the textblock the code worked perfectly. Could you explain why that is so I don't run into this problem in future?Pipage
I added some explanation. You were mixing up two issues.Hamartia

© 2022 - 2024 — McMap. All rights reserved.