【问题标题】:How to retrieve the CaretPosition from the WPF RichTextBox during GotFocus?如何在 GotFocus 期间从 WPF RichTextBox 中检索 CaretPosition?
【发布时间】:2012-07-27 15:43:39
【问题描述】:

我有一个 TextBox 和一个 RichTextBox 具有相同的文本。每次我在 RichTextBox 内单击时,TextBox 都应该以相同的插入符号位置聚焦。 我的第一个想法是:

void richTextBox_GotFocus(object sender, RoutedEventArgs e)
{
     vat textRange = new TextRange(rtfBox.Document.ContentStart, rtfBox.CaretPosition);
     plainTextBox.Focus();
     plainTextBox.CaretIndex = textRange.Text.Length;
}

但问题是 RichTextBox 还不知道事件处理程序中的 CaretPosition。

有什么解决方法吗?

也许是 RichTextBox 的子类化?

【问题讨论】:

  • 您尝试过 GotKeyboardFocus 活动吗?

标签: c# .net wpf textbox focus


【解决方案1】:

如果您使用 Dispatcher.BeginInvoke 运行该代码,则应在 WPF 确定插入符号位置等之后调用它。

例如

private void RichTextBox_GotFocus(object sender, RoutedEventArgs e)
{
    Dispatcher.BeginInvoke(new Action(UpdateTextBoxCaretPosition));
}

void UpdateTextBoxCaretPosition()
{
    var textRange = new TextRange(rtfBox.Document.ContentStart, rtfBox.CaretPosition);
    plainTextBox.Focus();
    plainTextBox.CaretIndex = textRange.Text.Length;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 2013-02-06
    • 1970-01-01
    • 2015-09-22
    相关资源
    最近更新 更多