WPF实现更加灵活绑定复杂Command(使用Microsoft XAML Behaviors 库)

1、安装NuGet

2、在XAML的命名空间引入:

cs 复制代码
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"

3、使用:

cs 复制代码
<Canvas Background="Aqua">
    <Rectangle Stroke="Red" 
               Width="{Binding RectModel.RectangleWidth}" 
               Height="{Binding RectModel.RectangleHeight}" 
               Canvas.Left="{Binding RectModel.RectangleLeft}" 
               Canvas.Top="{Binding RectModel.RectangleTop}"/>
    <i:Interaction.Triggers>
        <!--EventName是Command指定的Action-->
        <i:EventTrigger EventName="MouseDown">
            <i:InvokeCommandAction Command="{Binding MouseDownCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Canvas>

--我这里的ViewModel部分是这样子的

cs 复制代码
public SimpleCommand MouseDownCommand { get; private set; }   
// 构造方法中初始化
MouseDownCommand = new SimpleCommand { DoExecute = new Action<object>(MouseDown) };


/// <summary>
/// 鼠标按下的命令执行逻辑
/// </summary>
/// <param name="obj"></param>
/// <exception cref="NotImplementedException"></exception>
private void MouseDown(object obj)
{
    Debug.WriteLine("触发Canvas的MouseDown命令");
}


/// SimpleCommand类是这样的:
public class SimpleCommand : ICommand
{
    public event EventHandler CanExecuteChanged;
    public Action<object> DoExecute { get; set; }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        if (DoExecute != null)
        {
            DoExecute(parameter);
        }
    }
}

4、这样就可以在ViewModel中直接给这个Command内容了,不用像之前那么麻烦地绑定Command了,这样更加清晰,Command也可以有花样地组合

相关推荐
Bofu-16 小时前
【键盘测试】05-WPF 可视化键盘布局配置 + 全局钩子按键检测实战
wpf·键盘测试·全局键盘钩子·scancode·组合键检测
bugcome_com16 小时前
WPF 路径动画完全指南:自绘制控件实战
wpf
带娃的IT创业者18 小时前
Microsoft Edge 密码泄露事件深度剖析:当“安全”成为幻影
安全·microsoft·edge·microsoft edge·密码安全·内存安全·明文存储
yuanpan18 小时前
Python + Pillow 实战:开发一个图片批量格式转换工具
python·microsoft·pillow
V搜xhliang02462 天前
OpenClaw进阶完全教程
运维·人工智能·算法·microsoft·自动化
Soari2 天前
深度办公革命:拆解 Claude for Microsoft 365,打造金融级智能办公生态
python·microsoft·金融·flask
专注VB编程开发20年2 天前
专业分析python底层调用与按键精灵,ah3等的对比,hookdll,内存加载,调用.net dll
开发语言·javascript·python·microsoft·php·.net
V搜xhliang02462 天前
【进阶篇】OpenClaw 高级技巧:定时任务 + 子 Agent + 自动化工作流
运维·人工智能·算法·microsoft·自动化
量子炒饭大师2 天前
【Linux系统编程】Cyberpunk在霓虹丛林中构建堡垒 ——【Linux环境配置 与 基础指令】
linux·运维·microsoft·linux指令
大强同学2 天前
精简版Windows如何安装微软商城应用? Codex 离线安装教程
人工智能·microsoft