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

相关推荐
阿乔外贸日记12 小时前
外贸风控|美国市场7大类欺诈模式解析与风控框架
大数据·人工智能·物联网·microsoft·智能手机
ShineWinsu13 小时前
对于Qt:QWidget通用属性的解析—上
数据库·qt·microsoft·面试·gui·属性·qwidget
染指111016 小时前
160.Agent-LangGraph-自定义主管架构智能体
人工智能·windows·microsoft·langchain·1024程序员节·agents
wuyk5551 天前
PyQt6-第10讲-PDF工具箱
python·microsoft·pdf·pyqt
鬼手点金2 天前
缓存作为架构约束
开发语言·前端·人工智能·python·microsoft·缓存·架构
Vic.Tang2 天前
一次元数据管理项目投标后,我对 Microsoft Purview的初识一
microsoft·purview
小羊没烦恼!2 天前
分布式事务 | 使用DTM 的Saga 模式
java·linux·运维·数据库·wpf
贾伟康2 天前
【共创稿事节】第一张服务卡片:2×2 今日菜谱的克制设计
microsoft·harmonyos·arkts·鸿蒙
Shell运维手记2 天前
Shell 结构化命令知识点总结(case、for、while)
运维·microsoft·shell·脚本
2501_944525762 天前
开源鸿蒙平台 KMP_CMP 三方库「Atrium」适配全流程
microsoft·开源·harmonyos