以下是如何获取具有明显换行符的完整文本。
注意:
- 在您的项目中包含高级文本格式示例中的以下类:
- CustomTextSource
- FontRendering
- GenericTextProperties
- CustomTextSource类中提到了一些限制。然而,我相信这些限制不会影响您的要求。
- 这些只是示例。您可能需要根据自己的需求修改代码。
- 该代码仍使用一个技巧(尽管是不错的技巧)-
InputTextBox.ViewportWidth
。您可能需要测试最终输出是否与所需完全一致。
请参见:高级文本格式和高级文本格式示例
示例代码
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;
}