WPF命令绑定核心是ICommand接口,推荐用RelayCommand实现解耦与自动启停;需在属性变更后调用CommandManager.InvalidateRequerySuggested刷新状态,RoutedCommand适用于跨控件共享或快捷键场景。

WPF 中命令绑定的核心是 ICommand 接口,它让 UI 操作(比如按钮点击)和业务逻辑解耦,比直接写 Click 事件更灵活、可测试、支持自动启停(如按钮灰化)。下面用最常用也最实用的方式讲清楚怎么用。
WPF 自身没提供 ICommand 的默认实现,但社区广泛使用 RelayCommand(也叫 DelegateCommand)——它用 Action 和 Func 封装执行逻辑和判断逻辑,轻量又直观。
public class RelayCommand : ICommand<br>{<br> private readonly Action _execute;<br> private readonly Func<bool> _canExecute;<br><br> public RelayCommand(Action execute, Func<bool> canExecute = null)<br> {<br> _execute = execute;<br> _canExecute = canExecute ?? (() => true);<br> }<br><br> public bool CanExecute(object parameter) => _canExecute();<br> public void Execute(object parameter) => _execute();<br><br> public event EventHandler CanExecuteChanged<br> {<br> add => CommandManager.RequerySuggested += value;<br> remove => CommandManager.RequerySuggested -= value;<br> }<br>}public class MainViewModel<br>{<br> public ICommand SaveCommand { get; }<br><br> public MainViewModel()<br> {<br> SaveCommand = new RelayCommand(OnSave, CanSave);<br> }<br><br> private void OnSave() => MessageBox.Show("已保存");<br> private bool CanSave() => !string.IsNullOrWhiteSpace(Title); // 假设有个 Title 属性<br>}把按钮的 Command 属性直接绑定到 ViewModel 的 ICommand 属性,WPF 会自动调用 Execute,并根据 CanExecute 结果控制是否启用。
<Button Content="保存" Command="{Binding SaveCommand}" /><Button Content="删除" Command="{Binding DeleteCommand}" CommandParameter="{Binding SelectedItem}" />命令能否执行不是一成不变的,比如输入框为空时“保存”按钮应禁用。WPF 不会自动监听你的属性变化,得手动通知。
private string _title;<br>public string Title<br>{<br> get => _title;<br> set<br> {<br> _title = value;<br> OnPropertyChanged(); // INotifyPropertyChanged 实现<br> CommandManager.InvalidateRequerySuggested(); // 关键!告诉 WPF 重新查 CanExecute<br> }<br>}如果你需要响应 Ctrl+S、或让多个控件共用一个命令(比如“复制”在菜单和工具栏都可用),用 WPF 自带的 RoutedCommand 更合适。
public static class ApplicationCommands<br>{<br> public static readonly RoutedCommand Save = new RoutedCommand();<br>}<Window.CommandBindings><br> <CommandBinding Command="local:ApplicationCommands.Save" <br> Executed="OnSaveExecuted" <br> CanExecute="OnSaveCanExecute"/><br></Window.CommandBindings>
private void OnSaveExecuted(object sender, ExecutedRoutedEventArgs e)<br>{<br> MessageBox.Show("RoutedCommand 保存");<br>}<br><br>private void OnSaveCanExecute(object sender, CanExecuteRoutedEventArgs e)<br>{<br> e.CanExecute = !string.IsNullOrEmpty(Title);<br>}基本上就这些。RelayCommand + Binding 是日常开发主力,RoutedCommand 用在需要路由或跨控件共享的场景。不复杂但容易忽略 CommandManager.InvalidateRequerySuggested 这一步——少了它,按钮状态就不会自动更新。
以上就是WPF怎么使用命令绑定 WPF ICommand接口实现教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号