0

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

我的主窗体上有一个粗体按钮。当按下它时,它会做我需要它做的事情,即将选定的文本变为粗体,反之亦然。粗体按钮在按下时也会变成浅蓝色,然后再次按下时变回灰色。如此甜蜜,有效...

//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);
        }

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

4

2 回答 2

1

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

查看此页面以了解路由命令的工作原理:
如何:创建 RoutedCommand

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

这是一个帮助您入门的好页面:RichTextBox 概述

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

于 2015-06-05T02:28:24.013 回答
0

嘿 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));

    }
于 2015-06-05T11:38:20.253 回答