WPF TextBox 在焦点上改变颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35541735/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:41:14  来源:igfitidea点击:

WPF TextBox change color on focus

c#.netwpf

提问by Ivan

I try to change color on my input box when is focused.

我尝试在聚焦时更改输入框的颜色。

First I declare input button:

首先我声明输入按钮:

<TextBox x:Name="usernameTextBox"
         HorizontalAlignment="Left"
         Height="23" 
         Margin="115,31,0,0"
         TextWrapping="Wrap"
         VerticalAlignment="Top"
         Width="277"
         GotFocus="usernameTextBox_GotFocus"/>

And below I try to add style for that textbox

下面我尝试为该文本框添加样式

<Style x:Key="usernameTextBox"
       TargetType="{x:Type TextBox}">
      <Style.Triggers>
          <Trigger Property="IsFocused"
                   Value="true">
               <Setter Property="Background"
                       Value="{StaticResource OnMouseOverColor}" />
         </Trigger>
    </Style.Triggers>
</Style>

Error:

错误:

Error 1 A value of type 'Style' cannot be added to a collection or dictionary of type 'UIElementCollection'. D:\VS\VIM\VIM_WPF\login.xaml 15 9 VIM_Wpf

错误 1 ​​无法将“样式”类型的值添加到“UIElementCollection”类型的集合或字典中。D:\VS\VIM\VIM_WPF\login.xaml 15 9 VIM_Wpf

Any other solution how to fix this?

任何其他解决方案如何解决这个问题?

回答by Bogey

Either you define your style as a resource (e.g. in your usercontrol / window's resources), and then do something like

要么将样式定义为资源(​​例如在用户控件/窗口的资源中),然后执行类似的操作

<TextBox Style="{StaticResource theKeyOfYourStyle}" ..../>

or you explicitly set it in the TextBox:

或者您在 TextBox 中明确设置它:

<TextBox x:Name="usernameTextBox" HorizontalAlignment="Left" Height="23" Margin="115,31,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="277" GotFocus="usernameTextBox_GotFocus">
  <TextBox.Style>
    <Style TargetType="{x:Type TextBox}">
       <Style.Triggers>
         <Trigger Property="IsFocused" Value="true">
           <Setter Property="Background" Value="{StaticResource OnMouseOverColor}" />
         </Trigger>
       </Style.Triggers>
     </Style>
   </TextBox.Style>
</TextBox>