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

相关推荐
诺未科技_NovaTech1 小时前
微软生态技术实践:上海诺未全栈数字化与 AI 落地解决方案深度解析
人工智能·microsoft
哥本哈士奇1 小时前
微软 SQL Server 版本演进史:从诞生到 SQL Server 2025
microsoft
QYR-分析1 小时前
全球微型电声元器件行业发展现状、市场机遇及前景分析
microsoft
不会编程的懒洋洋2 小时前
WPF 性能优化+异步+渲染
开发语言·笔记·性能优化·c#·wpf·图形渲染·线程
飞Link13 小时前
OpenAI 与微软“非排他性”协议解读:AI 云计算市场将迎来百家争鸣?
人工智能·microsoft·云计算
zandy10111 天前
联想集团:AI创新标杆,定义智能时代企业创新新范式
大数据·人工智能·microsoft·联想
Allen Su1 天前
【Mac 教程系列第 19 篇】如何将 macOS 中的 Microsoft AutoUpdate 软件从系统中删除
microsoft·macos·autoupdate
求学中--1 天前
状态管理一文通:@State、@Prop、@Link、@Provide/Consume全解析
人工智能·小程序·uni-app·wpf·harmonyos
江沉晚呤时1 天前
用 C# 玩转 Scriban:自动生成报告、代码、文本,效率提升 10 倍
数据库·microsoft·c#·.net
熊文豪2 天前
从零到一的AI产品演进:用Claude Code与蓝耘MaaS打造多模型聚合聊天工具全纪实
人工智能·microsoft·蓝耘