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也可以有花样地组合

相关推荐
Soari14 分钟前
深度办公革命:拆解 Claude for Microsoft 365,打造金融级智能办公生态
python·microsoft·金融·flask
专注VB编程开发20年1 小时前
专业分析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
郑寿昌18 小时前
AI Agent 2026:从对话到行动的跃迁
人工智能·microsoft·数据挖掘
勤劳的进取家1 天前
服务器文件交互方式
运维·服务器·microsoft
飞Link1 天前
巨头混战医疗 AI!OpenAI、Anthropic 与微软的 Healthcare 助理技术架构对比
人工智能·microsoft·架构
葡萄城技术团队1 天前
AI没有缓解IT与业务的矛盾,有时反而激化了它
人工智能·microsoft