背景:实现按钮鼠标移动到上方有点交互效果或变一下有阴影。这样使用触发器就行了,但是如果是每个控件都有效果的话使用行为更加合适
1、下载NuGet包:Microsoft.xaml.behavior.wpf
2、创建行为类EffectBehavior,对Behavior进行重写
cs
public class EffectBehavior : Behavior<FrameworkElement>
{
protected override void OnAttached()
{
base.OnAttached();
// 这个时候的AssociatedObject就是FrameworkElement,因为泛型传过去了
AssociatedObject.MouseMove += AssociatedObject_MouseMove; // 鼠标进入
AssociatedObject.MouseLeave += AssociatedObject_MouseLeave;
}
private void AssociatedObject_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
var element = sender as FrameworkElement;
// 设置效果
element.Effect = (Effect)new DropShadowEffect() { Color = Colors.Transparent, ShadowDepth = 0 };
}
private void AssociatedObject_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
var element = sender as FrameworkElement;
element.Effect = (Effect)new DropShadowEffect() { Color = Colors.Red, ShadowDepth = 0 };
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.MouseMove -= AssociatedObject_MouseMove; // 鼠标进入
AssociatedObject.MouseLeave -= AssociatedObject_MouseLeave;
}
}
-- 就是简单加上鼠标移动到控件上面加上阴影效果
-- 抽象类Behavior的泛型传入的是FrameworkElement是因为,大多数控件都是由它派生出来的,具体可以查看这个文章的WPF控件结构:https://www.cnblogs.com/zh7791/p/11372473.html
3、在xaml中引入NuGet的命名空间
4、将自己重写的behavior给控件使用
XML
<StackPanel>
<TextBox Width="100" Height="30" Margin="40">
<i:Interaction.Behaviors>
<local:EffectBehavior/>
</i:Interaction.Behaviors>
</TextBox>
<Button Width="100" Height="30" Margin="40">
<i:Interaction.Behaviors>
<local:EffectBehavior/>
</i:Interaction.Behaviors>
</Button>
</StackPanel>
总结:对Behavior进行重写罢了
同样也是这个NuGet的使用
WPF实现更加灵活绑定复杂Command(使用Microsoft XAML Behaviors 库)_wpf 绑定复杂类型-CSDN博客