以下是如何获得明显换行符的完整文本。
注:
- 包括从Advanced Text Formatting Example以下类项目中的:
- CustomTextSource
- FontRendering
- GenericTextProperties
- 有其在CustomTextSource提到的一些限制类。不过,我相信您的要求不受这些限制的影响。
- 这些只是例子。您可能需要根据需要修改代码。
- 该代码仍然使用黑客(虽然体面的) -
InputTextBox.ViewportWidth
。您可能需要根据需要测试最终输出是否为,确切地说是。
见:Advanced Text Formatting和Advanced 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;
}
我很抱歉,但无法理解的问题,统计EMENT。是否要复制该文本框中的文本,并在其他位置粘贴时想保留被包装的位置? – publicgk 2011-04-19 18:35:03
作为文字还是视觉/图像? – 2011-04-19 18:45:22
@publicgk,我确切的情况是将文本传递给主动报告,同时保留包装的位置,所以我得到了与屏幕上显示的相同的包装。所以我需要它作为文本。 – Fbeauche 2011-04-19 18:54:25