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

相关推荐
小鹿软件办公41 分钟前
微软为 Windows 10、11 及 Server 安装镜像发布 Defender 更新
microsoft·defender
小刘的干货分享1 小时前
微软必应搜索推广:触达高价值决策层的PC端独占流量
microsoft·搜索引擎·微软
薛定猫AI1 小时前
【技术干货】DeepSeek 桌面智能体应用全解析:开源 AI Agent 平台实战部署与 API 调用指南
人工智能·microsoft
AIHR数智引擎3 小时前
AI组织进化论:拆解微软、英伟达、Anthropic与Open AI如何重写组织
人工智能·经验分享·microsoft·职场和发展·aihr
OPMR17 小时前
【已解决】微软输入法输入英文间隔变大(微软全字符切换)
程序人生·microsoft
技术钱18 小时前
langGraph基础组件介绍(二)
microsoft
影寂ldy21 小时前
C# 索引器(Indexer)超全笔记【基础 + 重载 + 实战练习】
windows·microsoft
带娃的IT创业者1 天前
穿越回 1980:解读微软开源的“最早 DOS 源码”与操作系统的原点
microsoft·微软·开源·操作系统·dos·源码解析·计算机历史
稷下元歌1 天前
七天学会plc加机器视觉之AI 接入 外设模块开发全详细操作文档(全程配套视频按文档实操)
python·sql·qt·贪心算法·r语言·wpf·时序数据库
C137的本贾尼1 天前
【实战】实现一个带事务与索引的命令行图书借阅系统
数据库·microsoft·oracle