几何尺寸与公差论坛

 找回密码
 注册
查看: 246|回复: 1

RoutedUICommand的作用是?编写样例代码

[复制链接]
发表于 2023-7-23 06:48:59 | 显示全部楼层 |阅读模式
RoutedUICommand是WPF中的一个命令类,用于定义和处理用户界面上的命令操作。它可以在XAML中定义和使用,并且可以与菜单、工具栏、按钮等UI元素关联,以实现统一的命令处理逻辑。

以下是一个使用RoutedUICommand的样例代码:

csharp
public static class CustomCommands
{
    public static readonly RoutedUICommand Open = new RoutedUICommand(
        "Open",
        "Open",
        typeof(CustomCommands),
        new InputGestureCollection()
        {
            new KeyGesture(Key.O, ModifierKeys.Control)
        }
    );

    public static readonly RoutedUICommand Save = new RoutedUICommand(
        "Save",
        "Save",
        typeof(CustomCommands),
        new InputGestureCollection()
        {
            new KeyGesture(Key.S, ModifierKeys.Control)
        }
    );
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        CommandBinding openCommandBinding = new CommandBinding(
            CustomCommands.Open,
            OpenCommandExecuted,
            OpenCommandCanExecute
        );
        CommandBinding saveCommandBinding = new CommandBinding(
            CustomCommands.Save,
            SaveCommandExecuted,
            SaveCommandCanExecute
        );

        this.CommandBindings.Add(openCommandBinding);
        this.CommandBindings.Add(saveCommandBinding);

        this.InputBindings.Add(new KeyBinding(
            CustomCommands.Open,
            new KeyGesture(Key.O, ModifierKeys.Control)
        ));
        this.InputBindings.Add(new KeyBinding(
            CustomCommands.Save,
            new KeyGesture(Key.S, ModifierKeys.Control)
        ));
    }

    private void OpenCommandExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        // 打开文件的逻辑
    }

    private void OpenCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        // 判断是否可以执行打开文件的命令
        e.CanExecute = true;
    }

    private void SaveCommandExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        // 保存文件的逻辑
    }

    private void SaveCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        // 判断是否可以执行保存文件的命令
        e.CanExecute = true;
    }
}
在上述代码中,我们定义了两个RoutedUICommand:Open和Save。然后,在MainWindow的构造函数中,我们创建了两个CommandBinding,将这两个命令与对应的命令处理方法关联起来。同时,我们还创建了两个KeyBinding,将这两个命令与快捷键关联起来。这样,当用户点击菜单、工具栏按钮或按下快捷键时,就会触发对应的命令处理方法。"
 楼主| 发表于 2023-7-23 06:50:23 | 显示全部楼层
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|Archiver|小黑屋|几何尺寸与公差论坛

GMT+8, 2024-5-8 17:00 , Processed in 0.084574 second(s), 21 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表