WPF 定义Command

时间:2023-03-09 06:24:33
WPF 定义Command

无参Command:

 internal class DelegateCommand : ICommand
{
private readonly Action _execute;
private readonly Func<bool> _canExecute; public DelegateCommand(Action execute) : this(execute, null) { }
public DelegateCommand(Action execute, Func<bool> canExecute)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
} public void Execute(object parameter)
{
_execute();
}
public bool CanExecute(object parameter)
{
if (_canExecute == null) return true;
return _canExecute();
} public event EventHandler CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
}

有参Command:

     internal class DelegateCommand<T> : ICommand
{
private readonly Action<T> _execute;
private readonly Func<bool> _canExecute; public DelegateCommand(Action<T> execute) : this(execute, null) { }
public DelegateCommand(Action<T> execute, Func<bool> canExecute)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
} public void Execute(object parameter)
{
_execute((T)parameter);
}
public bool CanExecute(object parameter)
{
if (_canExecute == null) return true;
return _canExecute();
} public event EventHandler CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
}

在viewmodel中,定义一个Command属性

 Command=new DelegateCommand<string> (searchText=>{
  //添加逻辑
});

然后绑定即可。

 <Window x:Class="WpfApp21.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModels="clr-namespace:WpfApp21.ViewModels"
xmlns:local="clr-namespace:WpfApp21"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<viewModels:SearchWordViewModel/>
</Window.DataContext>
<StackPanel>
<TextBox x:Name="InputTextBox"></TextBox>
<Button Command="{Binding SearchCommand}" CommandParameter="{Binding ElementName=InputTextBox,Path=Text}"></Button>
</StackPanel>
</Window>