Gig*_*igi 2 wpf text-formatting richtextbox
我正在尝试为 WPF 中的 RichTextBox 实现非常简单的文本格式化功能。它仅由 RichTextBox 上方的一些粗体、斜体等切换按钮组成。请参见下图,但忽略顶部的文本框 - RichTextBox 是底部较大的文本框。

切换所选内容或插入符号位置(对于将要输入的文本)的格式不是问题,因为我正在这样做:
private void BoldButton_Checked(object sender, RoutedEventArgs e)
{
this.SetSelectionBold(true);
}
private void BoldButton_Unchecked(object sender, RoutedEventArgs e)
{
this.SetSelectionBold(false);
}
private void SetSelectionBold(bool isBold)
{
var selection = this.RichText.Selection;
if (selection != null)
{
selection.ApplyPropertyValue(TextElement.FontWeightProperty, isBold ? FontWeights.Bold : FontWeights.Normal);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果用户将插入符号移动到其他位置(例如从粗体文本到普通文本),那么我希望 ToggleButtons 能够反映该状态,其方式与在 Word 中的工作方式大致相同。是否可以检测插入符位置何时发生变化,并采取相应的措施?
让自己陷入SelectionChanged事件并获取当前插入符位置,并测试该属性是否存在于该选择中?
在这种情况下,您可能想要类似的东西:
var selection = richTextBox.Selection;
if(selection != null)
{
if(selection.GetPropertyValue(TextElement.FontWeightProperty) == FontWeights.Bold)
// todo; enable your button
}
Run Code Online (Sandbox Code Playgroud)
如果该事件不是由插入符定位触发的(文档没有提及任何相关内容),您可能需要继承 RichTextBox 并 override OnSelectionChanged,之后您需要实际生成自己的插入符,例如:
var currentCaretPlusOne = new TextRange(richTextBox.CaretPosition,
richTextBox.CaretPosition+1);
if(currentCaretPlusOne != null)
{
if(currentCaretPlusOne.GetPropertyValue(TextElement.FontWeightProperty)
== FontWeights.Bold)
// todo; enable your button
}
Run Code Online (Sandbox Code Playgroud)