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

相关推荐
公子小六1 天前
基于.NET的Windows窗体编程之WinForms图像控件
windows·microsoft·c#·.net·winforms
贪玩的小松鼠1 天前
WPF基础到企业应用系列7——深入剖析依赖属性(WPF/Silverlight核
wpf
一只小bit1 天前
LangChain 核型组件与消息管理及提示词模版
windows·microsoft·langchain
界面开发小八哥1 天前
界面控件DevExpress WPF v26.1新版亮点 - TreeView、Spreadsheet控件功能升级
.net·wpf·界面控件·devexpress·ui开发
Nontee1 天前
Set 这个东西,跟我一开始想的不太一样
java·linux·windows·microsoft
大意的百合1 天前
Electron 应用如何上架微软商店:从 MSIX 打包到商店提交
javascript·microsoft·electron
XUHUOJUN1 天前
Windows Server 2025 Stretch Cluster 架构详解
windows·microsoft·azure local
纸小铭1 天前
Azure MCP 工具现已内置集成至 Visual Studio 2022,无需额外安装扩展
microsoft·azure·visual studio
XUHUOJUN1 天前
Windows Server 2025 RAC vs Stretch Cluster 技术定位
windows·microsoft·azure local
小鹿软件办公2 天前
微软确认 Windows 11 26H2 将调整系统默认备份机制
microsoft·windows 11 26h2