Following btnTest_Click(...)
event in my WPF .NET5
app successfully displays the content of a RichTextBox
into a FlowDocumentReader
. But, as shown in the images below, the different page viewing modes of the FlowDocumentReader
create excessive amounts of whitespace on lines. Question: Why it is happening, what I may be missing here, and how can we resolve the issue?
MainWindow.xaml
<Window x:Class="Wpf_RTBFlowDocTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Wpf_RTBFlowDocTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<DockPanel Name="mainPanel">
<ToolBar Name="mainToolBar" Height="30" DockPanel.Dock="Top">
<Button x:Name="btnTest" Content="Test" Click="btnTest_Click"/>
</ToolBar>
<RichTextBox Name="rtbTest" AcceptsTab="True" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"/>
<FlowDocumentReader x:Name="fdReader" ScrollViewer.VerticalScrollBarVisibility="Auto" IsScrollViewEnabled="True">
<FlowDocument IsOptimalParagraphEnabled="True" IsHyphenationEnabled="True" TextAlignment="Left"></FlowDocument>
</FlowDocumentReader>
</DockPanel>
</Grid>
</Window>
MainWindow.xaml.cs
private void btnTest_Click(object sender, RoutedEventArgs e)
{
var range = new TextRange(rtbTest.Document.ContentStart, rtbTest.Document.ContentEnd);
if (!range.IsEmpty)
{
if(fdReader.Document.Blocks.Count > 0)
fdReader.Document.Blocks.Clear();
using (var stream = new MemoryStream())
{
range.Save(stream, DataFormats.XamlPackage);
var copyto = new TextRange(fdReader.Document.ContentEnd, fdReader.Document.ContentEnd);
copyto.Load(stream, DataFormats.XamlPackage);
}
}
rtbTest.Visibility = Visibility.Collapsed;
fdReader.Visibility = Visibility.Visible;
}
Original display of the app before clicking the Test
button:
Single pageview display after the above code ran:
Single Scroll pageview display after above code ran:
Multiple pageview display after the above code ran:
That's exactly as expected: your source text file is including lots of NewLine
characters for line feed inside the sentences and spaces used for lines content alignment:
In a flow document, the content adapts itself to fit the container, but NewLine
characters inside sentences prevented the FlowDocument
control to format the text correctly.
Therefore, it's necessary to make some source text processing before loading it to the FlowDocument
control.