WPF行为

背景:实现按钮鼠标移动到上方有点交互效果或变一下有阴影。这样使用触发器就行了,但是如果是每个控件都有效果的话使用行为更加合适

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

相关推荐
Vicky&James6 分钟前
WPF到Web的无缝过渡:英雄联盟客户端项目OpenSilver迁移实战
前端·wpf
苏克贝塔7 分钟前
WPF11-附加属性
wpf
苏克贝塔8 分钟前
WPF13-MVVM进阶
wpf
吾与谁归in3 小时前
C#实现本地Deepseek模型及其他模型的对话
人工智能·c#·wpf·deepseek
lisenustc1 天前
WPF学习之Prism(二)
学习·wpf
百里与司空3 天前
WPF基本布局基础
学习·wpf
qq_382391334 天前
WPF框架学习
学习·wpf·1024程序员节
CE贝多芬4 天前
WPF的页面设计和实用功能实现
c#·wpf
酷炫码神4 天前
WPF布局控件
wpf
code_shenbing4 天前
WPF 实现虚拟键盘
c#·wpf