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

相关推荐
Aevget12 小时前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(一)
c#·wpf·界面控件·devexpress·ui开发
SEO_juper13 小时前
用户体验就是新SEO:如何同时提升搜索者满意度和搜索排名
microsoft·搜索引擎·ux·数字营销·seo优化
电手15 小时前
微软宣布删除“另存为”选项,今后文件将默认保存到云盘
windows·microsoft·电脑·onedrive·windows11·windows10
CsharpDev-奶豆哥2 天前
ASP.NET中for和foreach使用指南
windows·microsoft·c#·asp.net·.net
The Sheep 20232 天前
WPF自定义路由事件
大数据·hadoop·wpf
阳光雨滴2 天前
使用wpf用户控件编程落石效果动画
c++·wpf
wuty0072 天前
WPF 调用 ChangeWindowMessageFilterEx 修改指定窗口 (UIPI) 消息筛选器的用户界面特权隔离
wpf·sendmessage·changewindowmessagefilterex·uip·消息筛选器的用户界面特权隔离·window message
攻城狮CSU3 天前
WPF中核心接口 INotifyPropertyChanged
wpf
c#上位机3 天前
wpf之Interaction.Triggers
c#·wpf
是木子啦3 天前
wpf passwordbox控件 光标移到最后
c#·wpf