C#MouseLeftButtonDown 绑定命令
时间: 2023-07-06 15:43:33 浏览: 70
要将C#中的MouseLeftButtonDown事件绑定到命令,可以使用以下代码:
1. 在XAML中添加事件触发器:
```
<Button Content="Click Me" MouseLeftButtonDown="Button_MouseLeftButtonDown"/>
```
2. 在C#中创建命令和命令绑定器:
```
public class MyCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
// 命令要执行的代码
}
}
public class MyCommandBinding : DependencyObject
{
public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
"Command", typeof(ICommand), typeof(MyCommandBinding), new PropertyMetadata(null, CommandPropertyChanged));
public static ICommand GetCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(CommandProperty);
}
public static void SetCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(CommandProperty, value);
}
private static void CommandPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var element = obj as UIElement;
if (element != null)
{
element.MouseLeftButtonDown += (sender, args) =>
{
var command = e.NewValue as ICommand;
if (command != null && command.CanExecute(null))
{
command.Execute(null);
}
};
}
}
}
```
3. 在XAML中绑定命令:
```
<Button Content="Click Me" local:MyCommandBinding.Command="{Binding MyCommand}"/>
```
这将使用自定义的命令绑定器将命令绑定到MouseLeftButtonDown事件。当按钮被点击时,命令将被执行。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)