Csharp/C#教程:WPF:从文本框中获取“包装”文本分享


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

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

 

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

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

注意:

  • 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("rn"); } 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 ),其中每个项目代表视线,您将需要一个复杂的解决方案。
    此外,如果您只需要文本框中显示的文本的可见部分,则需要一些复杂的解决方案。

    上述就是C#学习教程:WPF:从文本框中获取“包装”文本分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

    本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

    ctvol管理联系方式QQ:251552304

    本文章地址:https://www.ctvol.com/cdevelopment/1041853.html

    (0)
    上一篇 2022年1月29日
    下一篇 2022年1月29日

    精彩推荐