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

相关推荐
专注VB编程开发20年1 天前
Webbrowser控件加载IE不同版本内核-注册表设置
microsoft·ie·webbrowser
小梦爱安全2 天前
SQL Server(Linux)安装
数据库·microsoft·sqlserver
小章UPUP2 天前
主流LLM API格式概述
microsoft
专注VB编程开发20年2 天前
为何Win内置SQLite却缺驱动?微软只为保住Access中小企业市场,office码头
数据库·microsoft·sqlite
小李云雾2 天前
FastAPI重要知识点补充-reponse与request的区别
microsoft·fastapi·request·response
烟话62 天前
MVVM核心机制:属性通知与命令绑定解析
wpf
Azure DevOps3 天前
Azure DevOps Server:2026年4月份补丁(安装详细步骤)
运维·microsoft·azure·devops
AI先驱体验官3 天前
臻灵:数字人+大模型,实时交互的技术临界点在哪里
大数据·人工智能·深度学习·microsoft·重构·开源·交互
xier_ran3 天前
【C++】static 关键字与 const 关键字的作用
java·数据库·microsoft
2401_832635583 天前
小白分享如何Go 语言中的图形界面开发:从 GUI 到 WebAssembly
microsoft·golang·wasm