Wpf 检测RichTextBox中插入符号位置的变化
我试图在WPF中为RichTextBox实现非常简单的文本格式功能。这只是由RichTextBox上方的几个粗体、斜体等切换按钮组成。请参见下图,但忽略顶部的文本框-RichTextBox是底部较大的文本框 切换所选内容或插入符号位置的格式(对于将键入的文本)不是问题,因为我正在执行以下操作:Wpf 检测RichTextBox中插入符号位置的变化,wpf,richtextbox,text-formatting,Wpf,Richtextbox,Text Formatting,我试图在WPF中为RichTextBox实现非常简单的文本格式功能。这只是由RichTextBox上方的几个粗体、斜体等切换按钮组成。请参见下图,但忽略顶部的文本框-RichTextBox是底部较大的文本框 切换所选内容或插入符号位置的格式(对于将键入的文本)不是问题,因为我正在执行以下操作: private void BoldButton_Checked(object sender, RoutedEventArgs e) { this.SetSelection
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);
}
}
但是,如果用户将插入符号移动到其他位置(例如,从粗体文本到普通文本),则我希望切换按钮反映该状态,其方式与Word中的工作方式大致相同。是否可以检测插入符号位置何时更改,并采取相应的措施?将自己挂接到
SelectionChanged
事件中,获取当前插入符号位置,并测试该选择上是否存在该属性
在这种情况下,您可能需要以下内容:
var selection = richTextBox.Selection;
if(selection != null)
{
if(selection.GetPropertyValue(TextElement.FontWeightProperty) == FontWeights.Bold)
// todo; enable your button
}
如果该事件不是由插入符号定位触发的(文档没有对此进行任何说明),
您可能需要从RichTextBox继承并覆盖选择更改后的
,然后您需要实际生成自己的插入符号,例如:
var currentCaretPlusOne = new TextRange(richTextBox.CaretPosition,
richTextBox.CaretPosition+1);
if(currentCaretPlusOne != null)
{
if(currentCaretPlusOne.GetPropertyValue(TextElement.FontWeightProperty)
== FontWeights.Bold)
// todo; enable your button
}
将自己挂接到
SelectionChanged
事件中,获取当前插入符号位置,并测试该选择上是否存在该属性
在这种情况下,您可能需要以下内容:
var selection = richTextBox.Selection;
if(selection != null)
{
if(selection.GetPropertyValue(TextElement.FontWeightProperty) == FontWeights.Bold)
// todo; enable your button
}
如果该事件不是由插入符号定位触发的(文档没有对此进行任何说明),
您可能需要从RichTextBox继承并覆盖选择更改后的
,然后您需要实际生成自己的插入符号,例如:
var currentCaretPlusOne = new TextRange(richTextBox.CaretPosition,
richTextBox.CaretPosition+1);
if(currentCaretPlusOne != null)
{
if(currentCaretPlusOne.GetPropertyValue(TextElement.FontWeightProperty)
== FontWeights.Bold)
// todo; enable your button
}
第一种方法奏效了——我没想到它会这么简单。只有一件事,调用GetPropertyValue()时需要强制转换为FontWeight,以便执行比较。第一个方法起作用了——我没想到它会这么简单。只有一件事,调用GetPropertyValue()时需要强制转换为FontWeight,以便执行比较。