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

相关推荐
杜子不疼.5 小时前
AutoGen vs CrewAI vs LangGraph:2026年 Agent 框架怎么选?
c++·microsoft
枫叶丹419 小时前
【HarmonyOS 6.0】ArkUI Scroll组件新特性:手势缩放能力全解析
microsoft·华为·harmonyos
IOFsmLtzR1 天前
Flink Agents 源码解读 --- (5) --- ActionExecutionOperator
microsoft·flink·wpf
小邓睡不饱耶1 天前
花店花品信息管理系统开发实战:Python实现简易门店管理系统
服务器·python·microsoft
竹之却1 天前
【Microsoft Store】解决微软商店无法打开,MicrosoftStore 初始化失败,请尝试刷新 或稍后返回
microsoft·微软商店·microsoft store
Wave8451 天前
LVGL—组件介绍
microsoft
Ashmcracker1 天前
Codex Desktop如何接入Azure OpenAI?AI Foundry部署GPT‑5.3‑codex 实操
人工智能·gpt·microsoft·azure
公子小六1 天前
基于.NET的Windows窗体编程之WinForms布局简介
windows·microsoft·c#·.net
weitingfu1 天前
Excel VBA 入门到精通(一):宏录制与 VBE 环境详解
microsoft
zhengyquan1 天前
微软砸1.6万亿日元布局日本AI!
人工智能·microsoft