聚焦时如何轻松更改 WPF TextBox 的样式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15244145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I easily change the style of WPF TextBox when it gets focused?
提问by Nicolas
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").
我的 WPF 应用程序中有一个 TextBox,背景颜色为"Blue"。当它接收到焦点时,背景颜色默认变为“白色”。当 TextBox 获得焦点时,我希望背景颜色具有另一种颜色(比如"DodgerBlue")。
All I can find in the web are amazingly examples of styles or templates, defining all possible VisualStates of the TextBox.
我在网上能找到的都是令人惊奇的样式或模板示例,它们定义了 TextBox 的所有可能的 VisualStates。
Is it not possible to create a short template targeting only that specific situation (i.e. when the TextBox has focus)?
是否无法创建仅针对特定情况(即 TextBox 具有焦点时)的简短模板?
Thanks.
谢谢。
回答by Marc
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...
那应该做...

