如何解决FlowDocument 行上有太多空白
在我的 btnTest_Click(...)
应用程序中关注 WPF .NET5
事件成功地将 RichTextBox
的内容显示到 flowdocumentreader
中。但是,如下图所示,flowdocumentreader
的不同页面查看模式会在行上产生过多的空白。 问题:为什么会发生这种情况,我在这里可能遗漏了什么,我们如何解决这个问题?
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;
}
点击 Test
按钮前应用的原始显示:
解决方法
这完全符合预期:您的源文本文件在句子中包含许多用于换行的 NewLine
字符和用于行内容对齐的空格:
在流文档中,内容会自行调整以适应容器,但句子中的 NewLine
字符会阻止 FlowDocument
控件正确设置文本格式。
因此,在将其加载到 FlowDocument
控件之前,需要对其进行一些源文本处理。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。