Search code examples
c#wpfxamldatatrigger

How to Write DataTrigger to update the value of a Tag Property in a WPF TextBox?


I need to Write DataTrigger to update the value of a Tag Property in a WPF TextBox.

If the TextBox Text.Count >0 then update the Tag property to True otherwise False.

XAML Source Code:
<TextBox Text="WPF"  Tag="True">
    <TextBox.Triggers>
        <DataTrigger Property="Text" Value="0">
            <Setter Property="Tag" Value="False" />
        </DataTrigger>
    </TextBox.Triggers>
</TextBox>

Solution

  • Your code won't work because you can't put data triggers into a control's Triggers collection. What you actually need is a trigger in the control's Style.

    Try this instead:

    <TextBox Text="WPF" Tag="True">
        <TextBox.Style>
            <Style TargetType="{x:Type TextBox}">
                <Style.Triggers>
                    <DataTrigger Value="0"
                        Binding="{Binding Text.Length, RelativeSource={RelativeSource Self}}">
                        <Setter Property="Tag" Value="False" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>
    

    Note that this is not foolproof: if the text box contains only whitespace for example, then it may appear to be empty but the length of the text will be greater than zero.

    As the answers from user2946329 and ATM show, there are various ways of doing this in a <Style> trigger.