How can I easily change the style of WPF TextBox w

2019-06-25 12:11发布

问题:

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.

回答1:

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...