C# 如何使用TextRange替换跑步的字母?
我对FlowDocuments完全陌生,似乎在任何地方都找不到它 我创建了一个文本块,其中每个内联都是一个只包含一个单词的运行。内联线是在代码中创建的。然后,我使用TextRange替换运行中的一些字母。但是TextRange似乎没有替换运行的字符,而是清空运行并将字母附加到上一次运行 保留原始运行对象的原始TextBlock结构很重要,因为我将事件绑定到它们 我做错了什么?Text=Text实际在做什么 感谢您的帮助 范例C# 如何使用TextRange替换跑步的字母?,c#,wpf,textblock,flowdocument,C#,Wpf,Textblock,Flowdocument,我对FlowDocuments完全陌生,似乎在任何地方都找不到它 我创建了一个文本块,其中每个内联都是一个只包含一个单词的运行。内联线是在代码中创建的。然后,我使用TextRange替换运行中的一些字母。但是TextRange似乎没有替换运行的字符,而是清空运行并将字母附加到上一次运行 保留原始运行对象的原始TextBlock结构很重要,因为我将事件绑定到它们 我做错了什么?Text=Text实际在做什么 感谢您的帮助 范例 ---Before textrange-- <Run>
---Before textrange--
<Run>
6||perrla
</Run>
<Run>
1|| **NOTE THIS IS A SPACE IN THE RUN
</Run>
<Run>
5||nc/at
</Run>
--After textrange ---
<Run> **NOTE THE EMPTY RUN
</Run>
<Run>
5|| test **NOTE HOW TEST IS APPENDED TO THE SPACE OF THE PREVIOUS RUN
</Run>
<Run>
5||nc/at
</Run>
GetXaml来自Microsoft,我将其略微修改为:
void GetXaml(TextElement element)
{
// Position a "navigator" pointer before the opening tag of the element.
TextPointer navigator = element.ElementStart;
while (navigator.CompareTo(element.ElementEnd) < 0)
{
switch (navigator.GetPointerContext(LogicalDirection.Forward))
{
case TextPointerContext.ElementStart:
// Output opening tag of a TextElement
Console.WriteLine(String.Format("<{0}>", navigator.GetAdjacentElement(LogicalDirection.Forward).GetType().Name));
break;
case TextPointerContext.ElementEnd:
// Output closing tag of a TextElement
Console.WriteLine(String.Format("</{0}>", navigator.GetAdjacentElement(LogicalDirection.Forward).GetType().Name));
break;
case TextPointerContext.EmbeddedElement:
// Output simple tag for embedded element
Console.WriteLine(String.Format("<{0}>", navigator.GetAdjacentElement(LogicalDirection.Forward).GetType().Name));
break;
case TextPointerContext.Text:
// Output the text content of this text run
Console.WriteLine(String.Format("{0}||{1}", navigator.GetTextRunLength(LogicalDirection.Forward),
navigator.GetTextInRun(LogicalDirection.Forward)));
break;
}
// Advance the naviagtor to the next context position.
navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
}
}
这似乎是因为TextRange.Start始终具有逻辑方向或后退。因此,它将文本放在前一个元素中 也许我针对我的特殊情况所做的修复可以帮助您解决您自己的问题:
if (this.Selection.Start.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.ElementStart &&
this.Selection.End.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementEnd &&
this.Selection.Start.Parent == this.Selection.End.Parent && this.Selection.Start.Parent is Run)
{
((Run)this.Selection.Start.Parent).Text = "NewText";
}
if (this.Selection.Start.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.ElementStart &&
this.Selection.End.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementEnd &&
this.Selection.Start.Parent == this.Selection.End.Parent && this.Selection.Start.Parent is Run)
{
((Run)this.Selection.Start.Parent).Text = "NewText";
}