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

相关推荐
donk13142 天前
React Native for OpenHarmony 实战:三方库 react-native-circular-action-menu 的鸿蒙化适配指南
javascript·分布式·react native·react.js·wpf·harmonyos
donk13142 天前
React Native for OpenHarmony 实战:三方库 react-native-step-indicator 的鸿蒙化适配指南
分布式·react native·react.js·wpf·harmonyos
He BianGu2 天前
【笔记】WPF中RenderOptions类的详细功能
笔记·wpf
VidDown3 天前
上线三个月后的第一次事故:一个 Django 服务的日志、监控与故障复盘
数据库·python·django·wpf·音视频·视频编解码
He BianGu3 天前
【笔记】WPF中CachingHint的功能
笔记·wpf
He BianGu3 天前
【笔记】在WPF中BitmapScalingMode的作用
笔记·wpf
Vae_Mars3 天前
幂等性学习笔记
笔记·学习·wpf
samble4 天前
从零搭建灌装监控系统(十九):单元测试实战,xUnit + 内存SQLite + 反射测试私有方法
c#·wpf·mvvm·modbus·工业控制
光泽雨5 天前
路由概念和路由事件 继承链路 RadioButton的事件解析
wpf
samble5 天前
从零搭建灌装监控系统(十八):自定义控件,三色灯与状态指示
c#·wpf·mvvm·modbus·工业控制