gpt4 book ai didi

c# - 如何将垂直滚动条移动到出现单词的视口(viewport) - FlowDocument

转载 作者:太空宇宙 更新时间:2023-11-03 23:44:49 28 4
gpt4 key购买 nike

我的 XAML 文件中有以下带段落的 FlowDocument:

<FlowDocumentScrollViewer ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto">
<FlowDocument Name="fDocument" PagePadding="10" FontFamily="Segoe UI" FontSize="22">
<Paragraph Name="fdParagraph">
Those who have denied the reality of moral distinctions, may be
ranked among the disingenuous disputants; nor is it conceivable,
that any human creature could ever seriously believe, that all
characters and actions were alike entitled to the affection and
regard of everyone. The difference, which nature has placed
between one man and another, is so wide, and this difference is
still so much farther widened, by education, example, and habit,
that, where the opposite extremes come at once under our
apprehension, there is no scepticism so scrupulous, and scarce
any assurance so determined, as absolutely to deny all
distinction between them. Let a man's insensibility be ever so
great, he must often be touched with the images of Right and
Wrong; and let his prejudices be ever so obstinate, he must
observe, that others are susceptible of like impressions. The
only way, therefore, of converting an antagonist of this kind, is
to leave him to himself.
</Paragraph>
</FlowDocument>
</FlowDocumentScrollViewer>

有时,我可能有较大的文本内容,无法适应当前的视口(viewport)。

是否有可能以及如何将垂直滚动条移动到出现单词的视口(viewport)?

最佳答案

为此,您需要在 FlowDocument 中垂直放置 TextPointer,并调用 ScrollViewer 方法 ScrollToVerticalOffset.

简而言之,就是这样:

public static class FlowDocumentExtensions
{
public static void ScrollToWord(
this FlowDocument flowDocument,
ScrollViewer scrollViewer,
string word)
{
var currentText = flowDocument.ContentStart;

while (true)
{
TextPointer nextText =
currentText.GetNextContextPosition(
LogicalDirection.Forward);
if (nextText == null)
return;

TextRange txt = new TextRange(currentText, nextText);

int index = txt.Text.IndexOf(word, StringComparison.Ordinal);
if (index > 0)
{
TextPointer start = currentText.GetPositionAtOffset(index);

if (start != null)
{
var rect = start.GetCharacterRect(
LogicalDirection.Forward);
scrollViewer.ScrollToVerticalOffset(rect.Y);
}

return;
}

currentText = nextText;
}
}
}

如果您想了解如何从FlowDocument 获取ScrollViewer:Scroll a WPF FlowDocumentScrollViewer from code?

关于c# - 如何将垂直滚动条移动到出现单词的视口(viewport) - FlowDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27875482/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com