gpt4 book ai didi

c# - WPF:从文本框中获取 "wrapped"文本

转载 作者:太空狗 更新时间:2023-10-29 23:03:04 28 4
gpt4 key购买 nike

当 TextWrapping="Wrap"时,WPF 中是否有一种方法可以使文本格式化为文本框上显示的文本?

<TextBox   Width="200"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto" />

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

最佳答案

这里是如何获得带有明显换行符的完整文本。

注意:

  • 包括来自 Advanced Text Formatting Example 的以下类在你的项目中:
    • 自定义文本源
    • 字体渲染
    • 通用文本属性
  • CustomTextSource 类中提到了一些限制。不过,我相信您的要求不会受到这些限制的影响。
  • 这些只是示例。您可能希望根据需要修改代码。
  • 该代码仍然使用 hack(虽然是一个不错的 hack)- InputTextBox.ViewportWidth。您可能想要测试最终输出是否完全如您所愿。

参见:Advanced Text FormattingAdvanced Text Formatting Example

示例代码
XAML:

<Window x:Class="TextFormatterForWrappedText.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Width="200"
x:Name="InputTextBox"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto" Margin="23,12,280,241" />
<TextBox x:Name="FormattedDisplayTextBox" Height="172"
HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="23,105,0,0" Width="438" AcceptsReturn="True"
TextWrapping="Wrap" />
<Button HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="257,12,0,0" Height="23" Content="Copy"
Name="CopyButton" Width="129" Click="CopyButton_Click" />
</Grid>
</Window>

代码隐藏:

private void CopyButton_Click(object sender, RoutedEventArgs e)
{
List<string> 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<string> GetTextAsStringList()
{
List<string> stringList = new List<string>();
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;
}

关于c# - WPF:从文本框中获取 "wrapped"文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5720302/

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