命令系统概述
C# 命令系统(特别是 WPF 中的命令系统)是一种将 UI 操作与执行逻辑分离的机制,主要包含以下几个核心组件:
-
ICommand 接口:命令系统的核心
-
RoutedCommand:WPF 内置的命令实现
-
CommandBinding:连接命令与处理逻辑
-
输入绑定:将输入手势(如快捷键)与命令关联
ICommand 接口解析
public interface ICommand
{
// 命令能否执行
bool CanExecute(object parameter);
// 命令执行时触发
void Execute(object parameter);
// CanExecute状态变化时触发
event EventHandler CanExecuteChanged;
}
实现原理
1. 基本命令流程
-
命令触发(通过按钮点击、快捷键等)
-
检查CanExecute
-
执行Execute
-
通知CanExecuteChanged(当命令可用状态变化时)
2. 命令路由机制
WPF 中的 RoutedCommand
使用事件路由系统寻找命令处理程序:
-
从命令目标开始
-
向上冒泡通过可视化树
-
直到找到具有匹配 CommandBinding 的容器
代码实现示例
示例1:自定义命令实现
public class RelayCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Func<object, bool> _canExecute;
public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public bool CanExecute(object parameter) => _canExecute?.Invoke(parameter) ?? true;
public void Execute(object parameter) => _execute(parameter);
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
// 手动触发CanExecuteChanged
public void RaiseCanExecuteChanged() => CommandManager.InvalidateRequerySuggested();
}
示例2:在 ViewModel 中使用命令
public class MainViewModel : INotifyPropertyChanged
{
private string _name;
public string Name
{
get => _name;
set
{
_name = value;
OnPropertyChanged();
// 通知命令状态可能已改变
CommandManager.InvalidateRequerySuggested();
}
}
public ICommand SayHelloCommand { get; }
public MainViewModel()
{
SayHelloCommand = new RelayCommand(
execute: _ => MessageBox.Show($"Hello, {Name}!"),
canExecute: _ => !string.IsNullOrWhiteSpace(Name));
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
示例3:XAML 中绑定命令
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="命令示例" Height="350" Width="525">
<StackPanel>
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"
Margin="5" Padding="5"/>
<Button Content="打招呼"
Command="{Binding SayHelloCommand}"
Margin="5" Padding="5"/>
</StackPanel>
</Window>
<!-- 后台代码设置DataContext -->
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
}
示例4:使用 WPF 内置命令
<Window x:Class="WpfApp.CommandDemoWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="内置命令示例">
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Copy"
Executed="CopyCommand_Executed"
CanExecute="CopyCommand_CanExecute"/>
</Window.CommandBindings>
<StackPanel>
<TextBox x:Name="SourceTextBox" Text="可复制的文本" Margin="5"/>
<Button Command="ApplicationCommands.Copy"
Content="复制"
CommandTarget="{Binding ElementName=SourceTextBox}"
Margin="5" Padding="5"/>
</StackPanel>
</Window>
// 后台代码
private void CopyCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (e.Source is TextBox textBox)
{
Clipboard.SetText(textBox.Text);
}
}
private void CopyCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = !string.IsNullOrEmpty(SourceTextBox.Text);
e.Handled = true;
}
高级应用场景
1. 命令参数
<Button Command="{Binding EditCommand}"
CommandParameter="{Binding SelectedItem}"
Content="编辑"/>
2. 输入手势绑定
<Window.InputBindings>
<KeyBinding Key="S" Modifiers="Ctrl" Command="{Binding SaveCommand}"/>
<MouseBinding MouseAction="LeftDoubleClick" Command="{Binding OpenCommand}"/>
</Window.InputBindings>
3. 复合命令(Prism 库示例)
public class CompositeCommandViewModel
{
public CompositeCommand CompositeCommand { get; } = new CompositeCommand();
public CompositeCommandViewModel()
{
CompositeCommand.RegisterCommand(new RelayCommand(_ => DoTask1()));
CompositeCommand.RegisterCommand(new RelayCommand(_ => DoTask2()));
}
private void DoTask1() => Console.WriteLine("Task 1 executed");
private void DoTask2() => Console.WriteLine("Task 2 executed");
}
命令系统优势
-
关注点分离:UI 与业务逻辑解耦
-
状态管理:自动处理控件启用/禁用状态
-
重用性:同一命令可绑定到多个控件
-
测试性:命令逻辑易于单元测试
-
组合性:支持命令组合和复杂场景
常见实现模式
-
MVVM 模式:ViewModel 暴露命令属性
-
命令服务:集中管理应用程序命令
-
命令总线:用于复杂应用中的命令分发
命令系统是 WPF 架构的核心部分,合理使用可以大幅提高应用程序的可维护性和可测试性。