软件在展示软件协议或者免责声明的时候,一般使用RichTextBox控件。RichTextBox 控件可以显示纯文本、Unicode 纯文本或 RTF 格式文件。有时候目标计算机上没有安装office或者为避免版权问题,可使用读取txt文件的方式替代引用word插件来加载文件。
这里使用高级文档功能FlowDocument来承载文本文件的内容和设置内容格式。
1、首先在生成目录下新建Disclaimer文件夹放置声明文档Disclaimer.txt。文档内容为协议内容,如:

2、新建WPF应用程序,界面xaml:
<Window x:Class="RichTextBoxDemo.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:RichTextBoxDemo"
mc:Ignorable="d"
Title="RichTextBox" Height="600" Width="800" Loaded="Window_Loaded">
<Grid>
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
<RichTextBox x:Name="showInfo" Margin="30" Background="Transparent" IsReadOnly="True" Focusable="False" Cursor="Arrow"></RichTextBox>
</ScrollViewer>
</Grid>
</Window>
3、交互逻辑:
using System;
using System.IO;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace RichTextBoxDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
LoadDocument();
}
/// <summary>
/// 加载txt文本
/// </summary>
private void LoadDocument()
{
string filePath = AppDomain.CurrentDomain.BaseDirectory + @"Disclaimer\Disclaimer.txt";//文件路径
if(File.Exists(filePath))
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);//以只读方式打开源文件
try
{
using (StreamReader sr = new StreamReader(fs))
{
FlowDocument document = new FlowDocument();//承载文件内容
string content = sr.ReadToEnd();
string[] split = content.Split(new char[2] { '\r', '\n' });
foreach (string para in split)
{
if(para != "")
{
Paragraph paragraph = new Paragraph(new Run(para));
paragraph.FontFamily = new FontFamily("微软雅黑");//修改样式
paragraph.Foreground = new SolidColorBrush(Colors.Black);
if (para == "免责声明")
{
paragraph.FontSize = 26;
paragraph.TextAlignment = TextAlignment.Center;
}
else
paragraph.FontSize = 20;
document.Blocks.Add(paragraph);
}
}
this.showInfo.Document = document;
}
}
catch (Exception ex)
{
}
finally
{
fs.Close();
}
}
}
}
}
4、运行展示:

本文介绍如何在WPF应用中利用FlowDocument加载文本文件,如Disclaimer.txt,并详细展示了创建WPF界面的XAML代码以及处理文本样式的后台逻辑,以此替代依赖于RichTextBox或Office插件来显示协议内容。
1130

被折叠的 条评论
为什么被折叠?



