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

相关推荐
newbe365241 小时前
我们如何使用 impeccable 优化前端界面设计与实现稳定性
前端·人工智能·分布式·github·aigc·wpf
zzgnbfd658811 小时前
2026最新vibe coding入门实战:零基础快速落地全流程实测
人工智能·microsoft
码来的小朋友12 小时前
手把手教你用 Python + PyQt5 做一个可视化图片切图工具
开发语言·python·microsoft
神经智研社13 小时前
ROS2-5章:节点参数parameter详细讲解
windows·microsoft·机器人环境搭建·win11 ros2 开发环境
XUHUOJUN21 小时前
Azure Local离线模式PKI规划(系列篇之五)
microsoft·azure local
春日见1 天前
E2E自驾JD理解
人工智能·深度学习·算法·microsoft·transformer
编码者卢布2 天前
【Azure Storage Account】跨存储账号复制 Blob 会产生大量网络流量费用吗?
microsoft·flask·azure
Data-Miner18 天前
大语言模型+智能体AI,122页PPT详解落地应用培训!
人工智能·microsoft·语言模型
Chris _data18 天前
WPF 学习第三天 — Modbus RTU 串口通信
hadoop·学习·wpf
c++之路18 天前
备忘录模式(Memento Pattern)
c++·microsoft