Monday, March 24, 2014

WPF: Loading RTF document in RichTextBox from Embeded Resouce.

While developing a UI interface for Wix based bootstrapper,  I found that in WPF, Richtextbox Control is not same as it was in Windows Forms. So loading an RTF document in it was a little mess. However, while finding and digging for about two days, I finally came to a simple solution. Let’s say, my WPF project name is Surf.
  1. In your WPF projects, add a Resources.resx file (if its not already there).
  2. Add your RTFDoc.rtf in your Resources.resx file.
  3. Along with your Resources.resx file, there would be code behind file:Resources.Designer.cs. Open it and copy its namespace and Class name. In my case it is  Surf.Resources.Resource1

I used this to load rtf data in my WPF RichTextBox control. Here are the lines from the code behind of my XAML:

using Surf.Resources;
void Surface_Loaded(object sender, RoutedEventArgs e)         
{             
//Loading License Agreement document data.
MemoryStream memLicStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(Resource1.RTFDoc));             

this.MyRTFDocument.Selection.Load(memLicStream, DataFormats.Rtf);
}

System.IO.MemoryStream class is used here to load the rtf data from RTFDoc stored in Resource1.resx. And then it is loaded as a Selection in my RichTextBox Control (MyRTFDocument), while specifying Data Format as Rtf.

No comments: