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 小时前
从 Coder 到 Designer :电商团队数据研发的 Harness Engineering 实践
人工智能·microsoft·机器学习
FreeBuf_6 小时前
微软发布创纪录的622个补丁,包含两个正被利用的0Day漏洞
microsoft
FuckPatience1 天前
WPF GridView 列绑定时前端没有属性提示
wpf
狗蛋儿l1 天前
眼见为食GPass眼镜实战
microsoft
abcd_zjq1 天前
Visual studio community 2026 安装缺少 Microsoft.net.4.8.FullRedist.20H2
microsoft·.net·visual studio
界面开发小八哥1 天前
界面控件DevExpress WPF v26.1新版亮点 - 模板工具包 & MVVM功能全新升级
wpf·界面控件·devexpress·ui开发·.net 10
北冥you鱼1 天前
Go语言常用包使用指南:从标准库到第三方利器
开发语言·microsoft·golang
祸不单行11 天前
强化学习框架】Miles 项目技术分析---(1)--- 总体
microsoft
XUHUOJUN2 天前
Windows 2025架构深度分析之Stretch Cluster 延迟工程现实
windows·microsoft·架构·azure local
zandy10112 天前
嵌入式BI PaaS:重构企业应用的数据智能生态
microsoft·重构·paas