WPF:从文本框中获取“包装”文本

当TextWrapping =“Wrap”时,WPF中是否有一种方法可以使文本格式显示在文本框中?

 

我试过使用TextFormatter类,但它允许我将文本绘制到绘图上下文中,我只需要包含换行符的文本。

以下是如何获得具有明显换行符的完整文本。

注意:

  • 在项目中包含高级文本格式示例中的以下类:
    • CustomTextSource
    • FontRendering
    • GenericTextProperties
  • CustomTextSource类中提到了一些限制。 但是,我相信您的要求不受这些限制的影响。
  • 这些只是一些例子。 您可能希望根据需要修改代码。
  • 代码仍然使用hack(虽然是一个不错的) – InputTextBox.ViewportWidth 。 您可能想要测试最终输出是否完全符合要求。

请参阅: 高级文本格式和高级文本格式示例

示例代码
XAML:

        

代码隐藏:

 private void CopyButton_Click(object sender, RoutedEventArgs e) { List stringList = GetTextAsStringList(); StringBuilder sb = new StringBuilder(); foreach (string s in stringList) { sb.Append(s); sb.Append("\r\n"); } Clipboard.SetData(System.Windows.DataFormats.Text, sb.ToString()); FormattedDisplayTextBox.Clear(); FormattedDisplayTextBox.Text = sb.ToString(); } private List GetTextAsStringList() { List stringList = new List(); int pos = 0; string inputText = InputTextBox.Text; CustomTextSource store = new CustomTextSource(); store.Text = inputText; store.FontRendering = new FontRendering(InputTextBox.FontSize, InputTextBox.TextAlignment, null, InputTextBox.Foreground, new Typeface(InputTextBox.FontFamily, InputTextBox.FontStyle, InputTextBox.FontWeight, InputTextBox.FontStretch)); using (TextFormatter formatter = TextFormatter.Create()) { while (pos < store.Text.Length) { using (TextLine line = formatter.FormatLine(store, pos, InputTextBox.ViewportWidth, new GenericTextParagraphProperties( store.FontRendering), null)) { stringList.Add(inputText.Substring(pos, line.Length - 1)); pos += line.Length; } } } return stringList; } 

为此,您必须使用文本测量API编写自己的逻辑。

第1将文本框文本刷新为单词。

步骤2:然后测量每个字宽并将它们组合,直到线宽小于文本框宽度。

请参阅此文章,其中介绍了文本测量过程。 (social.msdn.microsoft.com/forums/en-US/wpf/thread/…)

请参阅Ian Griffiths对此问题的回答: 从TextBlock中获取显示的文本

它从TextBlock获取显示的文本(因为它显示在屏幕上),但我认为你应该能够将它用于TextBox

如果您想要的只是文本框的文本(完整文本而不仅仅是可见部分),要在某个文本块的同一窗口中显示为文本(带有明显的换行符), 快速入侵可能是:

 FormattedText ft = new FormattedText(textBox1.Text, System.Globalization.CultureInfo.CurrentCulture, textBox1.FlowDirection, new Typeface(textBox1.FontFamily, textBox1.FontStyle, textBox1.FontWeight, textBox1.FontStretch), textBox1.FontSize, textBox1.Foreground); ft.TextAlignment = textBox1.TextAlignment; ft.Trimming = TextTrimming.None; ft.MaxTextWidth = textBox1.ViewportWidth; textBlock1.Width = textBox1.ViewportWidth; textBlock1.Height = ft.Height; textBlock1.TextAlignment = textBox1.TextAlignment; textBlock1.TextWrapping = textBox1.TextWrapping; textBlock1.Text = textBox1.Text; 

如果在其他地方需要它,您可以将值传送到该位置并在那里的文本块上使用它们。

如果您需要完整的文本(带有明显的换行符)作为字符串列表(例如List ),其中每个项目代表视线,您将需要一个复杂的解决方案。
此外,如果您只需要文本框中显示的文本的可见部分,则需要一些复杂的解决方案。