WPF 行为
一、前言
行为是一类事物的共同特征,可以向用户界面控件添加功能,而无需将其子类化。 功能是在行为类中实现的,并附加到控件上,就像它本身就是控件的一部分。
比如在鼠标进入/离开控件时,表现出不同的现象;给TextBox添加水印等
二,实例
我们现在创建一个Button行为,当鼠标进入时,将按键放大并添加与阴影,以实现浮动效果,离开时,复原
1. 创建一个类继承自Behavior
csharp
public class MyButtonBehavior : Behavior<Button>
我们自定义的行为需要继承自Behavior,并且需要指定该行为所用于的控件类型 ,该例子指定的关联对象类型为Button
2. 重写方法OnAttached()
在该方法中获取Button的宽和高,保存到字段中,并订阅Button的鼠标进入(MouseEnter)和鼠标离开事件(MouseLeave) AssociatedObject在这里就是所附加该行为的对象
在使用的过程中需要注意两点
- 在自己实现的行为中,需要重写两个虚方法OnAttached() 和OnDetaching(),在行为附加和分离时会分别调用这两个方法
- 在Behavior中有一个AssociatedObject的属性,该属性就是关联对象,也就是附加在控件对象
csharp
public class MyButtonBehavior : Behavior<Button>
{
private double m_Width;
private double m_Hight;
protected override void OnAttached()
{
base.OnAttached();
//回去button的宽和高
m_Width = AssociatedObject.Width;
m_Hight = AssociatedObject.Height;
AssociatedObject.MouseEnter += AssociatedObject_MouseEnter;
AssociatedObject.MouseLeave += AssociatedObject_MouseLeave;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.MouseEnter -= AssociatedObject_MouseEnter;
AssociatedObject.MouseLeave -= AssociatedObject_MouseLeave;
}
private void AssociatedObject_MouseLeave(object sender, MouseEventArgs e)
{
Button btn = sender as Button;
Storyboard storyboard = new Storyboard();
DoubleAnimation daw = new DoubleAnimation();
daw.Duration = TimeSpan.FromMilliseconds(100);
daw.To = m_Width;
DoubleAnimation dah = new DoubleAnimation();
dah.Duration = TimeSpan.FromMilliseconds(100);
dah.To = m_Hight;
Storyboard.SetTarget(daw, btn);
Storyboard.SetTargetProperty(daw, new PropertyPath("Width"));
Storyboard.SetTarget(dah, btn);
Storyboard.SetTargetProperty(dah, new PropertyPath("Height"));
storyboard.Children.Add(daw);
storyboard.Children.Add(dah);
storyboard.Begin();
btn.Effect = null;
}
private void AssociatedObject_MouseEnter(object sender, MouseEventArgs e)
{
Button btn = sender as Button;
//设置动画
Storyboard storyboard = new Storyboard();
DoubleAnimation daw = new DoubleAnimation();
daw.Duration = TimeSpan.FromMilliseconds(100);
daw.To = m_Width * 1.2;
DoubleAnimation dah = new DoubleAnimation();
dah.Duration = TimeSpan.FromMilliseconds(100);
dah.To = m_Hight * 1.2;
Storyboard.SetTarget(daw, btn);
Storyboard.SetTargetProperty(daw, new PropertyPath("Width"));
Storyboard.SetTarget(dah, btn);
Storyboard.SetTargetProperty(dah, new PropertyPath("Height"));
storyboard.Children.Add(daw);
storyboard.Children.Add(dah);
storyboard.Begin();
//设置阴影
DropShadowEffect dropShadowEffect = new DropShadowEffect();
dropShadowEffect.ShadowDepth = 1;
dropShadowEffect.BlurRadius = 10;
dropShadowEffect.Color = Color.FromRgb(221, 221, 221);
btn.Effect = dropShadowEffect;
}
}
安装NuGet包,Microsoft.Xmal.Behaviors.Wpf, 并在xaml界面引用命名空间 xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
csharp
<Button Content="Clear"
Margin="10 0 0 0"
Width="100"
Height="30">
<i:Interaction.Behaviors>
<local:MyButtonBehavior/>
</i:Interaction.Behaviors>
</Button>
这样就实现了鼠标进入放大,鼠标离开恢复原样的效果