2016-02-21 172 views
2

我试图在焦点时更改我的输入框上的颜色。WPF文本框在焦点上更改颜色

首先我声明输入按钮:

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

而且下面我尝试添加的风格为文本框

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

任何其他解决办法如何解决这一问题?

+0

什么不管用? – Phiter

+0

检查新更新 – Ivan

回答

6

要么你定义你的风格作为一种资源(例如,在你的用户控件/窗口的资源),然后像做

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

或明确设置它的文本框:

<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> 
+0

{“找不到名为'OnMouseOverColor'的资源,资源名称区分大小写。”} – Ivan

+0

'' This work – Ivan

+0

OnMouseOverColor:I take this来自您的代码示例。当然,这假定您实际上拥有一个资源,并在该文本框的可访问资源中的任何位置定义了“OnMouseOverColor”关键字 - 错误消息表明您没有。因此,确保您在文本框或其父元素之一中定义了该资源,并且其关键字是OnMouseOverColor。如果您不想为背景使用资源,则直接设置颜色(例如作为“黄色”)当然可以。 – Bogey

相关问题