检测 RichTextBox 中插入符号位置何时发生变化 [英] Detect when caret position changes in RichTextBox

查看:37
本文介绍了检测 RichTextBox 中插入符号位置何时发生变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 WPF 中的 RichTextBox 实现非常简单的文本格式功能.这仅由 RichTextBox 上方的一些粗体、斜体等 ToggleButton 组成.见下图,但忽略顶部的 TextBox - RichTextBox 是底部较大的一个.

I am trying to implement very simple text formatting functionality for a RichTextBox in WPF. This just consists of a few bold, italic, etc ToggleButtons just above the RichTextBox. See image below, but ignore the top TextBox - the RichTextBox is the bigger one at the bottom.

切换选择或插入符号位置的格式(对于将输入的文本)不是问题,因为我正在这样做:

Toggling formatting for either a selection or at the caret position (for text that will be typed in) is not a problem, as I'm doing this:

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

但是,如果用户将插入符号移动到其他地方(例如从粗体文本到普通文本),那么我希望 ToggleButtons 反映该状态,其方式与在 Word 中的工作方式大致相同.是否可以检测插入符号位置何时发生变化并采取相应措施?

However, if the user moves the caret somewhere else (e.g. from bold text to normal text) then I'd like the ToggleButtons to reflect that state, in much the same way as it works in Word. Is it possible to detect when the caret position changes, and take action accordingly?

推荐答案

将自己连接到 SelectionChanged 事件并获取当前插入符号位置,并测试该属性是否存在于该选择中?

Hook yourself into SelectionChanged event and get current caret position, and test if the property exists on that selection?

在这种情况下,您可能想要以下内容:

In the event, probably you want something like:

var selection = richTextBox.Selection;
if(selection != null)
{
  if(selection.GetPropertyValue(TextElement.FontWeightProperty) == FontWeights.Bold)
    // todo; enable your button
}

如果该事件不是由插入符号定位触发的(文档对此没有说明),您可能需要从 RichTextBox 继承并覆盖 OnSelectionChanged,之后您需要实际生成自己的 Caret,例如:

If that event is not triggered by caret positioning(the document doesn't say anything about that), you probably need to inherit from RichTextBox and override OnSelectionChanged, after that you need to actually generate your own Caret, eg:

var currentCaretPlusOne = new TextRange(richTextBox.CaretPosition, 
                  richTextBox.CaretPosition+1);
if(currentCaretPlusOne != null)
{
   if(currentCaretPlusOne.GetPropertyValue(TextElement.FontWeightProperty)
             == FontWeights.Bold)
        // todo; enable your button
}

这篇关于检测 RichTextBox 中插入符号位置何时发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆