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

相关推荐
小鹿软件办公15 小时前
微软公布更多 AI 功能加持的 Windows 11 全新“照片”应用
人工智能·microsoft
白雪讲堂16 小时前
从流量到增长:庞文英《GEO实战:AI时代的增长密码》重磅上市,开启AI营销新纪元
microsoft
acrel718 小时前
浅谈碳中和背景下企业绿色低碳转型
人工智能·物联网·microsoft
岁月刘声机19 小时前
国标实施|《法律法规电子文件》三项标准正式施行,电子文档可信闭环成关键
大数据·人工智能·microsoft
把我格子衫拿来19 小时前
本周科技热点:Meta 新模型、微软 Maia 300 与 AI 智能体新动向(10.12—10.15)
人工智能·科技·microsoft
Data-Miner20 小时前
数据分析,除了Excel数据透视表,还有什么工具?——2026 专业精选推荐榜
microsoft·数据分析·excel
阿乔外贸日记20 小时前
美国买家资产包装套路与应收款尽调框架,580万应收账款案例解析
大数据·服务器·人工智能·microsoft·云计算
donk13141 天前
React Native for OpenHarmony 实战:三方库 react-native-circular-action-menu 的鸿蒙化适配指南
javascript·分布式·react native·react.js·wpf·harmonyos
云表无代码开发1 天前
雷军救WPS“三次”!WPS注入新生力量,不再抄袭微软
大数据·microsoft
donk13142 天前
React Native for OpenHarmony 实战:三方库 react-native-step-indicator 的鸿蒙化适配指南
分布式·react native·react.js·wpf·harmonyos