如何将 rtf 文件加载到 Powershell 中的 WPF RichTextBox

Ben*_*Ben 2 wpf powershell richtextbox

有人知道我可以将 rtf 文件加载到 wpf RichTextBox 吗?

在 Windows.Forms 我会这样做

RichTextFile.Loadfile(c:\myfile.rtf) 
Run Code Online (Sandbox Code Playgroud)

但我不知道如何在 WPF 中实现相同的目标!

谢谢,

Zam*_*oni 6

不确定 PowerShell,但 RichTextBox 有一个 Document 属性,您可以使用它来加载 RTF 文件。
这是示例,以及一些对我有帮助的好网站:

这是 XAML:

<StackPanel>
    <RichTextBox Height="200" x:Name="rtb"/>
    <Button Content="Load" Click="Button_Click" Width="50" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

这是加载 RTF 的按钮单击事件:

public partial class MainView : Window
{
  public MainView()
  {
     InitializeComponent();
  }

  private void Button_Click(object sender, RoutedEventArgs e)
  {
     TextRange textRange;
     System.IO.FileStream fileStream;

     if (System.IO.File.Exists("Document.rtf"))
     {
        textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
        using (fileStream = new System.IO.FileStream("Document.rtf", System.IO.FileMode.OpenOrCreate))
        {
           textRange.Load(fileStream, System.Windows.DataFormats.Rtf);
        }
     }
  }
}
Run Code Online (Sandbox Code Playgroud)