【问题标题】:Where is ScrollToCaret in a TextBox in WPF?WPF 中 TextBox 中的 ScrollToCaret 在哪里?
【发布时间】:2012-11-29 08:23:41
【问题描述】:

我找不到那个功能。基本上我有一个多行文本框,当我执行搜索时,我会突出显示结果。但是,如果结果不在视图中,我将不得不手动向下滚动,直到找到突出显示的结果,这超出了“查找”功能的目的。

我不想使用 RichTextBox,因为我遇到了一些性能问题。

【问题讨论】:

    标签: c# wpf textbox


    【解决方案1】:

    您可以将GetLineIndexFromCharacterIndex 与ScrollToLine 结合使用:

    var selectionStart = x;
    var selectionLength = y;
    textBox.Select(selectionStart, selectionLength);
    textBox.ScrollToLine(textBox.GetLineIndexFromCharacterIndex(textBox.SelectionStart));
    

    【讨论】:

    • 注意你应该使用textBox.ScrollToLine(textBox.GetLineIndexFromCharacterIndex(textBox.SelectionStart)),而不是selectionStart。当您调用Select 时,WPF 映射超出文本长度的范围,如果您将过大的内容传递给GetLineIndexFromCharacterIndex,则会引发异常。
    • 像魅力一样工作。如果要查看Selection,需要关注Textbox textBox.Focus();
    • 如果您的文本水平离开屏幕,则不确定是否有效。它将进入行,但不会进入“列”。
    【解决方案2】:

    ScrollToLine 对我来说不够准确。我的文本框启用了换行,因此行索引不可靠。相反,我使用了这个:

    textBox.CaretIndex = selectionStart;
    textBox.ScrollToEnd();
    textBox.Select(selectionStart, selectionLength);
    

    基本上,ScrollToEnd 执行滚动到插入符号。

    【讨论】:

    • ScrollToEnd 完全按照它所说的:滚动到内容的末尾 Scrolls the view of the editing control to the end of the content. msdn.microsoft.com/en-us/library/… 甚至微软也这么说!
    猜你喜欢
    • 2023-03-18
    • 2011-05-28
    • 2010-12-18
    • 1970-01-01
    • 2011-06-15
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    相关资源
    最近更新 更多