Friday, May 25, 2018

[WPF] How to populate a Richtextbox with a content of a file in a nice way?

I have a following problem:

I have a TabControl with it's ItemsSource set to a Binding with an ObservableCollection object. Inside the Content property of TabControl I put a RichTextBox, to which I want to load a text file. Here is the XAML snippet:

 <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> 

With each new file, I want to be able to load the contents of the file to the RichTextBox using TextRange and FileStream objects like so:

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(); } } 

However, I don't know how to reference the RichTextBox in the ContentTemplate from code-behind level.

OpenedFiles is an ObservableColletion<OpenFile> object, where OpenFile is a class that contains the files' path, stream etc.

I kinda figured out a workaround. I created a MyTabItem class that derives from standard TabItem. This class puts a RichTextBox as it's Content in the constructor, so that I can populate it in code-behind. But I don't like that solution. I think it's ugly and there must be a better way. Sorry if that's a noob question - I am just learning this for my uni course and want to learn good practices, not flaky workarounds.

[WPF] How to populate a Richtextbox with a content of a file in a nice way? Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team