DelegateCommand 怎么绑定鼠标点击事件 获取按钮对象 和事件对象
时间: 2024-03-19 14:44:54 浏览: 18
要在 DelegateCommand 中获取按钮对象和事件对象,可以使用 CommandParameter 参数和 RoutedEventArgs 类型的参数。CommandParameter 允许我们将任何对象传递给命令的 Execute 和 CanExecute 方法中,而 RoutedEventArgs 类型的参数则是鼠标事件的参数类型。
以下是绑定鼠标点击事件、获取按钮对象和事件对象的示例代码:
1. 在 XAML 中,将按钮的 Command 属性绑定为 DelegateCommand 类型的 MyCommand 属性,并设置 CommandParameter 参数为按钮本身。例如:
```
<Button Content="Click me" Command="{Binding MyCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}" />
```
2. 在 ViewModel 中,获取按钮对象和事件对象,并进行操作。例如:
```
public DelegateCommand MyCommand { get; private set; }
public MyViewModel()
{
MyCommand = new DelegateCommand(ExecuteMyCommand);
}
private void ExecuteMyCommand(object parameter)
{
Button clickedButton = parameter as Button;
RoutedEventArgs eventArgs = Mouse.PrimaryDevice.ActiveSource.CurrentInputReport.InputSource.CurrentEventArgs as RoutedEventArgs;
// 在这里对 clickedButton 和 eventArgs 进行操作
}
```
在这个示例中,我们将按钮本身作为 CommandParameter 参数传递给了 MyCommand 命令,并在 ExecuteMyCommand 方法中将其转换为 Button 对象。同时,我们通过 Mouse.PrimaryDevice.ActiveSource.CurrentInputReport.InputSource.CurrentEventArgs 属性获取了当前鼠标事件的参数,并将其转换为 RoutedEventArgs 类型的对象。这样,我们就可以同时获取按钮对象和事件对象,并对它们进行操作了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)