【WPF命令绑定之--没有Command属性的控件如何进行命令绑定?】

前言

C#WPF之命令绑定

内容

有些控件不支持直接绑定命令,可以调用其他依赖实现命令的绑定。

依赖:Microsoft.Xaml.Behaviors.Wpf

使用如下代码可以实现事件的命令绑定,及传递参数:

1、引用:xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"

2、添加命令绑定代码( 如:代码①)

3、创建实现ICommand 的类public class EventsCommand : ICommand(如代码②)

4、创建命令 public ICommand LoadedWindowCommand{ get; set; }

5、初始化命令、并创建方法(如:代码③)

其中代码①写在**.xaml窗体视图中。代码②单独创建类。命令的初始化及方法绑定是创建在视图对应的ViewModel中如代码③。

代码①
csharp 复制代码
<!--绑定上下文-->
<Window.DataContext>
    <viewmodels:MainViewModel/>
</Window.DataContext>

<!--事件命令绑定-->
<behavior:Interaction.Triggers>
    <!--窗体加载命令绑定-->
    <behavior:EventTrigger EventName="Loaded">
        <behavior:InvokeCommandAction 
        	Command="{Binding LoadedWindowCommand}"   PassEventArgsToCommand="True"/>
    </behavior:EventTrigger>
    <!--窗体关闭命令绑定-->
    <behavior:EventTrigger EventName="Closing">
        <behavior:InvokeCommandAction 
        	Command="{Binding ClosingWindowCommand}" PassEventArgsToCommand="True"/>
    </behavior:EventTrigger>
</behavior:Interaction.Triggers>
代码②
csharp 复制代码
public class EventsCommand<T> : ICommand
{
    private readonly Action<T> _execute;
    private readonly Func<T, bool> _canExecute;
    public EventsCommand(Action<T> execute, Func<T, bool> canExecute = null)
    {
        _execute = execute ?? throw new ArgumentNullException(nameof(execute));
        _canExecute = canExecute;
    }
    public bool CanExecute(object parameter)
    {
        return _canExecute?.Invoke((T)parameter) ?? true;
    }
    public void Execute(object parameter)
    {
        _execute((T)parameter);
    }
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
}
代码③
csharp 复制代码
public class MainViewModel:INotifyPropertyChanged
{
	public ICommand LoadedWindowCommand { get; set; }
	public ICommand ClosingWindowCommand { get; set; }
	public MainViewModel()
	{
	    LoadedWindowCommand = new EventsCommand<object>(OnLoadedWindow);
		ClosingWindowCommand = new EventsCommand<object>(OnClosingWindow);
	}
	private void OnLoadedWindow(object e){}
	private void OnClosingWindow(object e){}
}

命令绑定例外

描述

有一种情况是控件里面添加控件,次数使用命令绑定传递参数。使用事件时,传递的一般是外层控件对象。

那么如何实现传递里面的对象呢,可以使用如下方法:使用DataContext数据上下文来传递。

csharp 复制代码
<ScrollViewer Background="#AEAEAE" x:Name="RecordScrollViewer">
    <ListBox ItemsSource="{Binding ChatRecordCollection}" Margin="5">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <!-- 显示消息内容 -->
                <TextBlock Text="{Binding Data}"  Margin="10,0,0,0">
                    <behavior:Interaction.Triggers>
                        <!--鼠标点击命令事件-->
                        <behavior:EventTrigger EventName="PreviewMouseDown">
                            <behavior:InvokeCommandAction
                             Command="{Binding DataContext.ChatRecordMouseDownCommand, 
                                RelativeSource={RelativeSource AncestorType=ListBox}}"
                             CommandParameter="{Binding}"
                             PassEventArgsToCommand="True"/>
                        </behavior:EventTrigger>
                    </behavior:Interaction.Triggers>
                </TextBlock>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</ScrollViewer>

结语

以上是个人日常学习中学到的一下知识,和理解。

相关推荐
Nicole Potter2 小时前
游戏中的成就系统,我们一般会使用设计模式中的哪种模式来制作?为什么?
游戏·设计模式·面试·c#
MZWeiei2 小时前
算法:判断链表是否有环
算法·链表·c#
椒颜皮皮虾྅4 小时前
【OpenVINO™】在 Intel Ultra AI PC 设备上使用 OpenVINO™ C# API本地部署YOLOv11与YOLOv12
人工智能·c#·openvino
CYX_cheng6 小时前
C#-委托
c#
Nicole Potter9 小时前
请说明字符串中 string str = null string str = ““ string str = string.Empty 三者的区别
游戏·unity·面试·c#
步、步、为营10 小时前
C# 应用程序中,输入法操控
开发语言·c#·.net
夏炎黄10 小时前
c# 代码规范
c#·代码规范
xcLeigh13 小时前
WPF高级 | WPF 与数据库交互:连接、查询与数据更新
数据库·c#·wpf·交互
Whappy00113 小时前
第一节:基于Winform框架的串口助手小项目---基础控件使用《C#编程》
开发语言·c#
qq_2979080115 小时前
asp.net运输公司车辆管理系统收入与费用统计软件车辆网上申请派车软件
sqlserver·开源·c#·asp.net