C# 将文件加载到TabItems中的不同RichTextBox中

C# 将文件加载到TabItems中的不同RichTextBox中,c#,wpf,xaml,richtextbox,C#,Wpf,Xaml,Richtextbox,我有以下问题: 我有一个TabControl,它的itemsource设置为与observedcollection对象绑定。在TabControl的Content属性中,我放置了一个RichTextBox,我想向其中加载一个文本文件。以下是XAML代码片段: <TabControl Grid.Column="0" x:Name="openFiles" ItemsSource="{Binding OpenedFiles}"> <TabCon

我有以下问题:

我有一个
TabControl
,它的
itemsource
设置为与
observedcollection
对象绑定。在
TabControl
Content
属性中,我放置了一个RichTextBox,我想向其中加载一个文本文件。以下是XAML代码片段:

        <TabControl Grid.Column="0" x:Name="openFiles" ItemsSource="{Binding OpenedFiles}">
            <TabControl.ItemTemplate>
                <!-- this is the header template-->
                <DataTemplate>
                    <TextBlock Text="{Binding name}" />
                </DataTemplate>
            </TabControl.ItemTemplate>
            <TabControl.ContentTemplate>
                <!-- this is the body of the TabItem template-->
                <DataTemplate>
                    <RichTextBox x:Name="fileTextBox"/>
                </DataTemplate>
            </TabControl.ContentTemplate>
        </TabControl>

但是,我不知道如何从代码隐藏级别引用
ContentTemplate
中的
RichTextBox

您是否介意发布OpenedFile项目的外观?谢谢您的关注。OpenedFiles是一个
observedcollection
对象,其中
OpenFile
是一个包含文件路径、流等的类。我找到了一个解决方法。我创建了一个从标准
TabItem
派生的
MyTabItem
类。这个类将
RichTextBox
作为
Content
放在构造函数中,这样我就可以在代码隐藏中填充它。但我不喜欢这个解决方案。我觉得这很难看,一定有更好的办法。抱歉,如果这是一个noob问题-我只是为了我的大学课程学习这个,我想学习好的实践,而不是简单的解决方法。看看这里发布的解决方案
if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{             
  TextRange range;
  System.IO.FileStream fStream;

  if (System.IO.File.Exists(openFile1.FileName))
  {
      range = new TextRange(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd);
      fStream = new System.IO.FileStream(openFile1.FileName, System.IO.FileMode.OpenOrCreate);
      range.Load(fStream, System.Windows.DataFormats.Rtf );

      fStream.Close();
  }
}