【发布时间】:2015-06-04 13:17:38
【问题描述】:
我正在研究一些 C# WPF,并正在创建一个简单的文字处理器来将普通文本转换为 wiki 标记。我是 WPF 的新手,遇到了一些看似微不足道的问题,希望可以轻松解决。
我的主窗体上有一个粗体按钮。当按下它时,它会做我需要它做的事情,即将选定的文本变为 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?我在下面创建了一个自定义 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 中做些什么吗?任何帮助将不胜感激,如果有任何不清楚或需要其他信息,请告诉我。谢谢大家!
【问题讨论】:
-
只是一个建议......不要重复代码,将
isBold = !isBold;放在if else语句之外并删除其中一个。另外,由于某种原因,当我使用按键手势时,粗体按钮没有改变颜色...这是因为您的boldText方法与Button无关。 -
好点,感谢谢里登的提示
-
如果
Ctrl和B被按下并且PreviewKeyUp处理程序以在之后将其恢复正常。 -
哦,crikey 没有意识到你第一条评论的后半部分 Sheridan,也感谢使用 PreviewKeyDown 处理程序的建议,我也会看看.当您说
boldText()方法与按钮无关时,我将如何解决?我的意思是它有这个:MainWindow.thisForm.btnBold.Background = Brushes.LightBlue; -
好吧,我已经为此奋斗了几个小时了。无论如何,您是否可以给我一个示例,说明我将如何在
boldText()方法中给出与按钮的关系,或使用 PreviewKeyDown 处理程序?
标签: wpf colors controls inputbinding