使用键盘快捷键 C# WPF 更改按钮颜色

Change button color using keyboard shortcut C# WPF

我正在研究一些 C# WPF,并且正在创建一个简单的文字处理器来将普通文本转换为 wiki 标记。我是 WPF 的新手,遇到了一些看似微不足道的问题,希望能轻松解决。

我的主窗体上有一个 Bold 按钮。当按下它时,它会做我需要它做的事情,即将选定的文本变为 bold ,再次按下时反之亦然。 Bold 按钮在按下时也会变成漂亮的浅蓝色,再次按下时又变回灰色。太甜了……

//Make Bold MAIN method
    static bool isBold = false;
    public static void boldText()
    {
        if (isBold == false)
        {

            TextSelection ts = MainWindow.thisForm.rtbMain.Selection;
           MainWindow.thisForm.btnBold.Background = Brushes.LightBlue;
            if (!ts.IsEmpty)
            {

                ts.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
            }
            isBold = !isBold;

        }
        else
        {

            MainWindow.thisForm.btnBold.Background = Brushes.LightGray;
            TextSelection ts = MainWindow.thisForm.rtbMain.Selection;
            ts.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Normal);
            isBold = !isBold;

        }

    }

我现在的问题是出于某种原因,当我使用 InputBinding 调用上面的代码时,选定的文本变为粗体,但按钮颜色没有改变...whaaaaA?我在下面创建了自定义 CommandExecuteCanExecute 命令:

  public class ToolBar
   {
     //Custom Command
           public static RoutedCommand boldShortCut = new RoutedCommand();

        //For use with Keybindings for BOLD command
            static bool canExecute = true;
            public static void myCommandExecute(object sender, ExecutedRoutedEventArgs e)
            {
                boldText();
                canExecute = !canExecute;
            }
            public static void myCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
            {
                e.CanExecute = true;
            }

然后我在主窗体的构造函数中创建 KeyGestureInputBindings

public MainWindow()
        {
            InitializeComponent();
            thisForm = this;
            initializeFeatures();

            KeyGesture kg = new KeyGesture(Key.B, ModifierKeys.Control);
            InputBinding ib = new InputBinding(ToolBar.boldShortCut, kg);
            this.InputBindings.Add(ib);
        }

所以这一切都有效,但由于某种原因,当我使用按键手势时 Bold 按钮没有改变颜色 (CTRL+B).在 XAML 中有什么我需要做的吗?任何帮助将不胜感激,如果有任何不清楚或需要其他信息,请告诉我。谢谢大家!

您正在创建的命令 (boldShortCut) 从未设置为执行任何操作。 RoutedCommand 仅在激活时触发事件。需要在树的某处绑定一个命令来侦听事件并执行一些逻辑。

查看此页面以了解路由命令的工作原理:
How to: Create a RoutedCommand

此外,当您按 Ctrl+B 时文本变为粗体的唯一原因是因为这是 RichTextBox 的内置功能。事实上,RichTextBox 有很多功能,您可以很容易地将工具栏按钮连接起来。在尝试重新实现其现有功能之前,学习如何使用 RichTextBox 可以节省很多时间。

这是一个很好的入门页面:RichTextBox Overview

(有关您可以连接的现有命令的完整列表,请参阅 EditingCommands Class 文档。)

嘿 Xavier 你完全正确,我没有在我的构造函数中将我的 Command 添加到 CommandBindings

请参阅下面更正的代码,该代码在构造函数中调用 boldShortcut 命令:

//Constructor
public MainWindow()
    {
        InitializeComponent();
        thisForm = this;
        initializeFeatures();

        ToolBar.boldShortCut.InputGestures.Add(new KeyGesture(Key.M, ModifierKeys.Control));
        CommandBindings.Add(new CommandBinding(ToolBar.boldShortCut, ToolBar.myCommand, ToolBar.myCommandCanExecute));

    }