Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I easily change the style of WPF TextBox when it gets focused?

I have a TextBox in my WPF app, with background color "Blue". When it receives focus, the background color changes to "White" by default. I want the background color to have another color when the TextBox gets focused (say "DodgerBlue").

All I can find in the web are amazingly examples of styles or templates, defining all possible VisualStates of the TextBox.

Is it not possible to create a short template targeting only that specific situation (i.e. when the TextBox has focus)?

Thanks.

like image 746
Nicolas Avatar asked Dec 11 '22 17:12

Nicolas


1 Answers

You can use a simple style trigger:

<TextBox>
        <TextBox.Style>
            <Style TargetType="{x:Type TextBox}">
                <Style.Triggers>
                    <Trigger Property="IsFocused" Value="True">
                        <Setter Property="Background" Value="Tomato" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>

That should do...

like image 136
Marc Avatar answered May 25 '23 06:05

Marc