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

相关推荐
观无4 小时前
关于wpf的自适应
wpf
干净的坏蛋4 小时前
Microsoft Word 中 .doc 和 .docx 的区别
microsoft·word
时光追逐者15 小时前
一款开源免费、通用的 WPF 主题控件包
开源·c#·.net·wpf
Leinwin15 小时前
微软智能语音平台赋能理想汽车:创新驱动,引领智能出行新体验
microsoft
甜甜不吃芥末1 天前
Windows 应用程序的 UI 框架:WPF、WinUI 3 和 UWP的差异区别
windows·ui·wpf
杰哥技术分享1 天前
宝塔 php支持sqlserver
microsoft
界面开发小八哥1 天前
界面组件DevExpress WPF中文教程:Grid - 如何检查节点?
ui·.net·wpf·界面控件·devexpress·ui开发
阿酷tony1 天前
微软语音合成标记语言SSML文档结构和事件(详细文档和实例)
microsoft·微软语音·ssml文档结构·ssml结构·ssml语音合成
qb_jiajia1 天前
2025年微软mos备考攻略-穷鬼版
microsoft·微软
FreeBuf_2 天前
微软365 PDF导出功能存在本地文件包含漏洞,可泄露敏感服务器数据
服务器·microsoft·pdf