当前位置: 首页 > news >正文

wpf 命令理解

命令包含RouteCommand和CustomCommand类

RouteCommand

通常用于自定义控件,或者入门学习时用

本身仅定义命令标识,必须通过 CommandBinding 关联执行逻辑,以下代码的CommandBinding是后台代码添加的Windows.CommandBinding.Add();

如果不是后台代码,用xaml语言的话

<Window.Resources>
<RoutedUICommand x:Key="PlayCommand" Text="Open"/>
</Window.Resources><Window.CommandBindings>
<CommandBinding Command="{StaticResource PlayCommand}"Executed="CommandBinding_Executed"CanExecute="CommandBinding_CanExecute"/>
</Window.CommandBindings>

后台代码

using System;
using System.Windows;
using System.Windows.Input;// 自定义命令类(使用RoutedCommand实现路由功能)
public static class CustomCommands
{// 声明命令public static readonly RoutedCommand Save = new RoutedCommand("Save",                  // 命令名称typeof(CustomCommands),  // 所属类型new InputGestureCollection  // 可选:定义快捷键{new KeyGesture(Key.S, ModifierKeys.Control)  // Ctrl+S});public static readonly RoutedCommand Delete = new RoutedCommand("Delete", typeof(CustomCommands),new InputGestureCollection{new KeyGesture(Key.Delete)  // Delete键});
}// 命令执行逻辑(通常在ViewModel或代码后台实现)
public class CommandHandler
{// 注册命令绑定public static void RegisterCommandBindings(UIElement element){// 保存命令绑定element.CommandBindings.Add(new CommandBinding(CustomCommands.Save,Save_Executed,       // 执行逻辑Save_CanExecute      // 能否执行的判断));// 删除命令绑定element.CommandBindings.Add(new CommandBinding(CustomCommands.Delete,Delete_Executed,Delete_CanExecute));}// 保存命令执行private static void Save_Executed(object sender, ExecutedRoutedEventArgs e){// 实际保存逻辑MessageBox.Show("执行保存操作");e.Handled = true;}// 保存命令是否可执行private static void Save_CanExecute(object sender, CanExecuteRoutedEventArgs e){// 这里可以根据条件判断是否允许执行(例如:数据是否已修改)e.CanExecute = true;  // 始终允许执行e.Handled = true;}// 删除命令执行private static void Delete_Executed(object sender, ExecutedRoutedEventArgs e){// 实际删除逻辑if (MessageBox.Show("确定要删除吗?", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes){MessageBox.Show("执行删除操作");}e.Handled = true;}// 删除命令是否可执行private static void Delete_CanExecute(object sender, CanExecuteRoutedEventArgs e){// 例如:只有选中项存在时才允许删除e.CanExecute = true;  // 简化示例,始终允许e.Handled = true;}
}
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;// 模拟RoutedCommand的核心实现
public class MyRoutedCommand
{// 命令元数据public string Name { get; }public Type OwnerType { get; }public InputGestureCollection InputGestures { get; }// 构造函数:初始化命令元数据public MyRoutedCommand(string name, Type ownerType, InputGestureCollection inputGestures = null){Name = name;OwnerType = ownerType;InputGestures = inputGestures ?? new InputGestureCollection();}// 执行命令:核心方法public void Execute(object parameter, IInputElement target){if (target == null) return;// 1. 创建命令执行事件参数var args = new ExecutedRoutedEventArgs(this, parameter){Source = target};// 2. 在目标元素上触发路由事件(冒泡)target.RaiseEvent(args);// 3. 如果事件未被处理,继续向上传播(简化逻辑)if (!args.Handled){var parent = VisualTreeHelper.GetParent(target as DependencyObject);if (parent is IInputElement parentElement){Execute(parameter, parentElement); // 递归向上查找处理者}}}// 判断命令是否可执行public bool CanExecute(object parameter, IInputElement target){if (target == null) return false;// 1. 创建可用性判断事件参数var args = new CanExecuteRoutedEventArgs(this, parameter){Source = target,CanExecute = false // 默认不可执行};// 2. 在目标元素上触发路由事件target.RaiseEvent(args);// 3. 如果未找到处理者,继续向上传播if (!args.Handled){var parent = VisualTreeHelper.GetParent(target as DependencyObject);if (parent is IInputElement parentElement){return CanExecute(parameter, parentElement);}}return args.CanExecute;}
}// 配套的路由事件参数(简化版)
public class ExecutedRoutedEventArgs : RoutedEventArgs
{public MyRoutedCommand Command { get; }public object Parameter { get; }public ExecutedRoutedEventArgs(MyRoutedCommand command, object parameter){Command = command;Parameter = parameter;RoutedEvent = CommandManager.ExecutedEvent; // 关联命令系统的执行事件}
}public class CanExecuteRoutedEventArgs : RoutedEventArgs
{public MyRoutedCommand Command { get; }public object Parameter { get; }public bool CanExecute { get; set; }public CanExecuteRoutedEventArgs(MyRoutedCommand command, object parameter){Command = command;Parameter = parameter;RoutedEvent = CommandManager.CanExecuteEvent; // 关联可用性判断事件}
}

CustomCommand类

继承ICommand,命名为RelayCommand或者DelegateCommand

在viewmodel中声明初始化

常用于MVVM开发

http://www.dtcms.com/a/477735.html

相关文章:

  • [好用工具] 一款mac/windows电脑历史剪切板工具,类似著名的Paste
  • 【Qt开发】输入类控件(七)-> QSlider
  • Oracle Exadata一体机简介 1千多个W
  • Caffeinated for Mac 防止屏幕睡眠工具
  • Trae官网炫酷特效与vue-bits的使用
  • 网站内页修改关键字抖音广告投放平台官网
  • Artstudio Pro for Mac 绘图与图片编辑软件
  • 上班没事做看什么网站wordpress主题官方
  • .NET Framework 4.0和Visual Studio 2010的串口通信类
  • 20自由度全驱动:赋能Tesollo五指灵巧手精细柔性作业新可能
  • 基于FastAPI与LangChain的Excel智能数据分析API开发实践
  • 【四级】全国大学英语四级历年真题及答案解析PDF电子版(2015-2025年6月)
  • 专业制造双轴倾角传感器与水平监测传感器的优质厂家分析
  • QtitanNavigation赋能工业制造:提升生产效率的界面导航利器
  • 网站不备案做优化网站建设 中软
  • 成都市建设厅网站查询建设部举报网站
  • 优秘智能深度学习应用场景实战提升效率指南
  • 【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
  • 做网站建议农业网站建设模板下载
  • xdma IP使用教程1-xdma ip核配置
  • Pytest参数化实战:高效测试API接口
  • 关于力扣第167场双周赛的第一二题赛后反思
  • Post-training of LLMs
  • 【学习总结】AI接口测试-零基础从接口概念到客达天下系统Apifox+DeepSeek接口测试实战全流程
  • 【苍穹外卖笔记】Day04--套餐管理模块
  • 初识redis(分布式系统, redis的特性, 基本命令)
  • [特殊字符] Avalonia + Silk.NET 加载 3D 模型时 GenBuffer 返回 0?这是个底层兼容性陷阱!
  • 学习threejs,打造交互式花卉生成器
  • Redis 学习笔记(二)
  • 北京展览馆网站建设wordpress插件排列