wpf button使用Command
时间: 2023-07-11 13:33:37 浏览: 63
WPF中的Button控件可以使用Command属性来绑定一个Command对象,当用户点击按钮时,Command对象的Execute方法将会被调用。
以下是一个示例:
首先,创建一个实现了ICommand接口的自定义命令类:
```
public class CustomCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Func<object, bool> _canExecute;
public CustomCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public event EventHandler CanExecuteChanged;
}
```
然后,在你的WPF窗口中,创建一个Button控件,并设置Command属性为自定义命令类的一个实例:
```
<Button Content="Click Me" Command="{Binding CustomCommand}" CommandParameter="Hello World" />
```
在窗口的ViewModel中,创建一个公共属性CustomCommand,该属性返回自定义命令类的一个实例:
```
public class MainWindowViewModel
{
public ICommand CustomCommand { get; }
public MainWindowViewModel()
{
CustomCommand = new CustomCommand(ExecuteCustomCommand, CanExecuteCustomCommand);
}
private void ExecuteCustomCommand(object parameter)
{
// Do something when the button is clicked
MessageBox.Show(parameter.ToString());
}
private bool CanExecuteCustomCommand(object parameter)
{
// Return true if the button can be clicked, false otherwise
return true;
}
}
```
这样,当用户点击按钮时,ExecuteCustomCommand方法将会被调用,并且传递"Hello World"作为参数。同时,CanExecuteCustomCommand方法将会被调用来确定按钮是否可以被点击。