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

相关推荐
霸道流氓气质2 小时前
Spring AI Function Calling实现原理与自定义函数
java·spring·microsoft
小弥儿4 小时前
GitHub今日热榜 | 2026-09-01:迷你小模型登场
学习·microsoft·开源·github
海盗12345 小时前
微软技术日报-2026-08-31
microsoft
小鹿软件办公5 小时前
微软官方提示:Windows 安全中心出现 Defender 已关闭为虚假告警
安全·microsoft
阿崽meitoufa6 小时前
Prompt Engineering for Agent:让 Agent 稳定运行的提示词写法
网络·人工智能·microsoft
海盗12346 小时前
微软技术日报-2026-09-01
microsoft
迪飞特科技6 小时前
分布式事务下 Spring 声明式事务失效的 3 种修复方案
分布式·spring·wpf
何以解忧,唯有..2 天前
Pydantic 介绍与使用:Python 数据校验的现代方案
数据库·python·microsoft
郝学胜-神的一滴2 天前
C++11 工程级应用 06:自己造一个类似Python的Range迭代器
开发语言·c++·windows·python·程序人生·microsoft