加载到richtextbox后,rtf布局发生变化wpf c#

时间:2015-06-09 07:14:20

标签: c# wpf text richtextbox rtf

我有一个rtf,当我用文字打开它时,布局显示完美,但当我尝试在我的wpf应用程序中的richtextbox中打开它时,布局已关闭,我希望保持相同。有办法做到这一点吗?阅读文件的另一种方式是什么?

以下是我用来加载rtf文件的代码

openFile.InitialDirectory = @"C:\";
openFile.Filter = "Text files (*.rtf)|*.rtf|All Files (*.*)|*.*";
openFile.RestoreDirectory = true;
openFile.Title = "Select Script";

if (openFile.ShowDialog() == true)
{
    string originalfilename = System.IO.Path.GetFullPath(openFile.FileName);

    TextRange range;
    FileStream fStream;

    if (openFile.CheckFileExists)
    {
         range = new TextRange(rtfMain.Document.ContentStart, rtfMain.Document.ContentEnd);
         fStream = new FileStream(originalfilename, System.IO.FileMode.OpenOrCreate);
         range.Load(fStream, DataFormats.Rtf);
         fStream.Close();
    }
}

这是xaml

 <RichTextBox IsReadOnly="True" x:Name="rtfMain" HorizontalAlignment="Left" Width="673" VerticalScrollBarVisibility="Visible"/>

这是原始的样子

enter image description here

这就是它在wpf

中的richtextbox中的样子

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

 if (openFile.CheckFileExists)
    {
      range = new TextRange(rtfMain.Document.ContentStart, rtfMain.Document.ContentEnd);
      using (var fStream = new StreamReader(originalfilename, Encoding.Default,true))
      {
        range.Text = fStream.ReadToEnd();
      }
    }

和xaml:

<RichTextBox IsReadOnly="True" x:Name="rtfMain" HorizontalAlignment="Left" 
                     Width="673" VerticalScrollBarVisibility="Visible" Height="250">
            <RichTextBox.Resources>
                <Style TargetType="{x:Type Paragraph}">
                    <Setter Property="Margin" Value="0"/>
                </Style>
            </RichTextBox.Resources>
        </RichTextBox>

它看起来如何: enter image description here