C#MouseLeftButtonDown事件如何 绑定命令
时间: 2023-07-07 14:42:16 浏览: 42
要将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事件。当按钮被点击时,命令将被执行。