我有以下XAML代码:
This is a RichTextBox - if you don't specify a width, the text appears in a single column
...如果在XAML中创建此窗口,您可以看到,当您没有为窗口指定宽度时,它会将文本包装在一个列中,一次一个字母.有什么我想念的吗?如果它是控制中已知的缺陷,是否有任何解决方法?
这是WPF RichTextBox的确认错误.要修复它,请将FlowDocument的PageWidth绑定到RichTextBox宽度,即
编辑:为FlowDocument命名,以便您可以在后面的代码中访问它,并且永远不会在代码隐藏中新建流文档.
尝试将FlowDocument的宽度(单向)绑定到容器RichTextBox的宽度.
为我工作......
本文中的方法对我有用:
WPF RichTextBox不提供将其宽度调整为文本的功能.据我所知,RichTextBox在其可视树中使用FlowDocumentView来呈现Flowdocument.它将占用可用空间来呈现其内容,因此不会根据内容调整其大小.由于这是一个内部类,我们似乎无法覆盖布局过程,让RichTextBox将其大小调整为文本.
因此,我认为您的方法是正确的方向.不幸的是,根据我的研究,没有直接的方法来测量RichTextBox中渲染文本的大小.
我们可以尝试一种解决方法.我们可以递归遍历RichTextBox中的flowdocument来检索所有Run和Paragraph对象.然后我们将它们转换为FormattedText以获得大小.
本文演示如何将FlowDocument转换为FormattedText.我还在该文章中使用FlowDocumentExtensions类编写了一个简单的示例.
public Window2() { InitializeComponent(); StackPanel layoutRoot = new StackPanel(); RichTextBox myRichTextBox = new RichTextBox() { Width=20}; this.Content = layoutRoot; layoutRoot.Children.Add(myRichTextBox); myRichTextBox.Focus(); myRichTextBox.TextChanged += new TextChangedEventHandler((o,e)=>myRichTextBox.Width=myRichTextBox.Document.GetFormattedText().WidthIncludingTrailingWhitespace+20); } public static class FlowDocumentExtensions { private static IEnumerableGetRunsAndParagraphs(FlowDocument doc) { for (TextPointer position = doc.ContentStart; position != null && position.CompareTo(doc.ContentEnd) <= 0; position = position.GetNextContextPosition(LogicalDirection.Forward)) { if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementEnd) { Run run = position.Parent as Run; if (run != null) { yield return run; } else { Paragraph para = position.Parent as Paragraph; if (para != null) { yield return para; } } } } } public static FormattedText GetFormattedText(this FlowDocument doc) { if (doc == null) { throw new ArgumentNullException("doc"); } FormattedText output = new FormattedText( GetText(doc), CultureInfo.CurrentCulture, doc.FlowDirection, new Typeface(doc.FontFamily, doc.FontStyle, doc.FontWeight, doc.FontStretch), doc.FontSize, doc.Foreground); int offset = 0; foreach (TextElement el in GetRunsAndParagraphs(doc)) { Run run = el as Run; if (run != null) { int count = run.Text.Length; output.SetFontFamily(run.FontFamily, offset, count); output.SetFontStyle(run.FontStyle, offset, count); output.SetFontWeight(run.FontWeight, offset, count); output.SetFontSize(run.FontSize, offset, count); output.SetForegroundBrush(run.Foreground, offset, count); output.SetFontStretch(run.FontStretch, offset, count); output.SetTextDecorations(run.TextDecorations, offset, count); offset += count; } else { offset += Environment.NewLine.Length; } } return output; } private static string GetText(FlowDocument doc) { StringBuilder sb = new StringBuilder(); foreach (TextElement el in GetRunsAndParagraphs(doc)) { Run run = el as Run; sb.Append(run == null ? Environment.NewLine : run.Text); } return sb.ToString(); } }