1. 添加dll
Microsoft.Expression.Interactions.dll
System.Windows.Interactivity.dll
2. 创建行为类
public class TextBoxBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.MouseEnter += AssociatedObject_MouseEnter;
this.AssociatedObject.MouseLeave += AssociatedObject_MouseLeave;
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.MouseEnter -= AssociatedObject_MouseEnter;
this.AssociatedObject.MouseLeave -= AssociatedObject_MouseLeave;
}
private void AssociatedObject_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
TextBox txb = (TextBox)sender;
txb.BorderBrush = new SolidColorBrush(Color.FromArgb(0xFF, 0x18, 0x90, 0xFF));
txb.BorderThickness = new Thickness(2);
}
private void AssociatedObject_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
TextBox txb = (TextBox)sender;
txb.BorderThickness = new Thickness(1);
}
}
其中需要重写两个方法-->OnAttached OnDetaching
OnAttached :使用this.AssociatedObject属性(表示当前作用的对象)将行为注册到事件中。
OnDetaching:使用this.AssociatedObject属性(表示当前作用的对象)将行为拆除到事件中。(不拆除会造成资源泄露)
3. 使用
<TextBox Text="123123">
<i:Interaction.Behaviors>
<local:TextBoxBehavior/>
</i:Interaction.Behaviors>
</TextBox>