Liang
Liang

Reputation: 937

A simple WPF trigger not works

I'm trying to set the width property of textbox when text is "ABC",however the trigger doesn't work. the width remains '40'.

        <TextBox Height="23" HorizontalAlignment="Left" Margin="295,211,0,0" Name="textBox1" VerticalAlignment="Top" Width="40"  Text="{Binding Text}"  >
            <TextBox.Style>
                <Style TargetType="TextBox">
                    <Style.Triggers>
                        <Trigger Property="Text" Value="ABC" >
                            <Setter Property="Width" Value="120"></Setter>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>

Upvotes: 0

Views: 181

Answers (1)

Richard E
Richard E

Reputation: 4919

You need to remove the Width property in the TextBox definition because this will take precedence over the Trigger. Set the Width in a Style setter as below:

    <TextBox Height="23" HorizontalAlignment="Left" Margin="295,211,0,0" Name="textBox1" VerticalAlignment="Top" Text="{Binding Text}"  >
        <TextBox.Style>
            <Style TargetType="TextBox">
                <Setter Property="Width" Value="40"/>
                <Style.Triggers>
                    <Trigger Property="Text" Value="ABC" >
                        <Setter Property="Width " Value="120"></Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>

UPDATE -

Local value has higher precedence compared to triggers. Refer to this - Dependency Property Value Precedence.

Upvotes: 1

Related Questions