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

相关推荐
yanaiding20 小时前
C# WPF 独立开发看图工具 PixSight 经验介绍(二)—— 水印模块开发实录
图像处理·c#·wpf·个人开发
starzy19901 天前
Soloop 智能视频创作全流程实战指南
数据库·microsoft·音视频
XUHUOJUN1 天前
Microsoft Entra Hybrid Identity Day-2 Operations 实战手册:用户、组、对象过滤、MIM 与故障排查
microsoft·microsoft 365
带娃的IT创业者1 天前
微软开源“AI Agents for Beginners”:一场面向初学者的智能体范式启蒙
人工智能·microsoft·微软·开源·react·ai智能体·初学者
光电的一只菜鸡2 天前
小白从零开始学agent(二)——如何高效编写 Prompt 与 Skill
hadoop·microsoft·prompt
Light Gao2 天前
MCPHub 路由原理:一个入口如何管理并调用上百个 MCP Server
windows·microsoft
阿米亚波2 天前
【C/C++包管理器】vcpkg(by microsoft)
c语言·c++·git·vscode·microsoft·github·vcpkg
梦想的旅途22 天前
企业微信自动化:自动发送文本、图片、文件
前端·数据库·microsoft
海盗12342 天前
微软技术日报——2026-08-06
人工智能·microsoft·.net
海盗12342 天前
微软技术日报——2026-08-07
python·microsoft·flask