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

相关推荐
三千道应用题1 小时前
WPF&C#超市管理系统(6)订单详情、顾客注册、商品销售排行查询和库存提示、LiveChat报表
开发语言·c#·wpf
✎ ﹏梦醒͜ღ҉繁华落℘19 小时前
开发WPF项目时遇到的问题总结
wpf
hqwest2 天前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
Vae_Mars2 天前
WPF中使用InputBindings进行快捷键绑定
wpf
hqwest2 天前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
hqwest2 天前
C#WPF实战出真汁01--项目介绍
开发语言·c#·wpf
wuty0073 天前
WPF 实现支持动态调整高度的文本显示控件
wpf·scrollviewer·extentheight·自动高度控件·动态调整高度
范纹杉想快点毕业6 天前
C 语言主控开发与显控开发能力体系及技术栈详解,STM32、QT、嵌入式、边缘系统显示
stm32·单片机·tcp/ip·microsoft·fpga开发·51单片机·wpf
weixin_447103586 天前
WPF之绑定!
c#·wpf
DataIntel6 天前
wpf问题记录
wpf