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

相关推荐
DN20209 小时前
当AI开始评估客户的“成交指数”
数据结构·人工智能·python·microsoft·链表
Sinowintop12 小时前
易连EDI-EasyLink之WebEDI功能解读
服务器·microsoft·php·edi·国产edi软件·webedi
山岚的运维笔记13 小时前
SQL Server笔记 -- 第34章:cross apply
服务器·前端·数据库·笔记·sql·microsoft·sqlserver
竟未曾年少轻狂14 小时前
Spring Boot 项目集成 Redis
java·spring boot·redis·缓存·消息队列·wpf·redis集群
光泽雨16 小时前
C#中Process类详解
microsoft·c#·交互
清风~徐~来16 小时前
【视频点播系统】Redis-SDK 介绍及使用
数据库·redis·wpf
棉晗榜17 小时前
WPF DataGrid鼠标滚不动,划不动解决
wpf
baivfhpwxf202317 小时前
wpf自适应布局
wpf
编码者卢布17 小时前
【Azure Event Hub】在VMSS中使用WAD(Window Azure Diagnostic)插件发送日志到Event Hub中报错分析
microsoft·azure
deephub1 天前
Agent Lightning:微软开源的框架无关 Agent 训练方案,LangChain/AutoGen 都能用
人工智能·microsoft·langchain·大语言模型·agent·强化学习