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

相关推荐
小白16 小时前
WPF自定义Dialog模板,内容用不同的Page填充
wpf
Crazy Struggle20 小时前
C# + WPF 音频播放器 界面优雅,体验良好
c#·wpf·音频播放器·本地播放器
James.TCG1 天前
WPF动画
wpf
He BianGu2 天前
笔记:简要介绍WPF中FormattedText是什么,主要有什么功能
笔记·c#·wpf
脚步的影子2 天前
.NET 6.0 + WPF 使用 Prism 框架实现导航
.net·wpf
jyl_sh2 天前
Ribbon (WPF)
ribbon·wpf·client·桌面程序开发·c/s客户端
wo63704312 天前
[Visual Stuidio 2022使用技巧]2.配置及常用快捷键
c#·.net·wpf
小黄人软件2 天前
wpf 字符串 与 变量名或函数名 相互转化:反射
wpf
界面开发小八哥3 天前
DevExpress WPF中文教程:如何解决排序、过滤遇到的常见问题?(二)
.net·wpf·界面控件·devexpress·ui开发
Vae_Mars3 天前
WPF中图片的宫格显示
wpf