我正在研究一些 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?我在下面创建了一个自定义Command、Execute和CanExecute命令:
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;
}
然后我在主窗体的构造函数中创建KeyGesture和InputBindings :
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 中做些什么吗?任何帮助将不胜感激,如果有任何不清楚或需要其他信息,请告诉我。多谢你们!