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

相关推荐
Stuomasi_xiaoxin18 小时前
微软office填表无法打勾✔,解决办法!
microsoft·mfc
界面开发小八哥20 小时前
界面控件DevExpress WPF v25.1新功能预览 - 数据网格、报表性能增强
wpf·界面控件·devexpress·ui开发·.net 9
Bruce_Liuxiaowei1 天前
网络安全应急响应-日志分析
安全·web安全·microsoft
宝桥南山1 天前
Model Context Protocol (MCP) - 尝试创建和测试一下MCP Server
microsoft·ai·微软·c#·.net·.net core
pound1271 天前
第五章.python函数
windows·python·microsoft
WineMonk1 天前
.NET WPF 可视化树(Visual Tree)
.net·wpf
FreeBuf_2 天前
微软Exchange管理中心全球范围宕机
microsoft
AI糊涂是福2 天前
数字政府与电子政务综合分析报告
经验分享·microsoft·政务
weisian1512 天前
Java常用工具算法-6--秘钥托管云服务3--微软zure Key Vault
java·microsoft·安全架构
ALex_zry2 天前
构建高可靠C++服务框架:从日志系统到任务调度器的完整实现
开发语言·c++·wpf