Setting the contents of a WPF RichTextBox

Posted by Chris on October 03, 2006

In the project I am currently working on we are using Windows Presentation Foundation for building the GUI. This means there are a lot of new things to learn. Even the small things take some time when you do not know which of the new controls to use are what properties and methods to use on these. (Of course it does not help that Resharper 2.0 does not know anything about XAML).

One such problem that I just had was working with a RichTextBox. The application should contain a text box where the users can enter text, using all the standard functionality such as bold, italics etc, and this information (text and markup) should be stored in the database. This was not as straightforward as it used to be in .Net 2.0 (or earlier). Since I guess other people will likely want to do the same thing I am posting the code I wrote to do this.

public string InputText
{
  get
  {
    string text = "";

    using(Stream stream = new MemoryStream())
    {
      TextRange contents = new TextRange(
        textBoxInputText.Document.ContentStart,
        textBoxInputText.Document.ContentEnd);

      contents.Save(stream, DataFormats.Xaml);

      stream.Position = 0;

      using(StreamReader reader = new StreamReader(stream))
      {
        text = reader.ReadToEnd();
      }
    }

    return text;
  }
  set
  {
    textBoxInputText.Document.Blocks.Clear();

    if(value != null && value.Length > 0)
    {
      using(Stream stream = new MemoryStream(
        UTF8Encoding.Default.GetBytes(value)))
      {
        TextRange contents = new TextRange(
              textBoxInputText.Document.ContentStart,
              textBoxInputText.Document.ContentEnd);

        contents.Load(stream, DataFormats.Xaml);
      }
    }
  }
}

The property InputText is part of the view interface for this page in our Model-View-Presenter architecture. The presenter uses this property to show/collect the value in the model.

Trackbacks

Trackbacks are closed.

  • Amin Pourhadi

    Thanks you a lot :)

  • Steve

    Thanks! Saved me a lot of time!!

  • Dan

    It's very helpful for me, thanks for sharing :)

  • Chris P

    This is great stuff. I commend your time and willingness to share. Please keep it up!

  • mick

    Very nice work. Exactly what I was after.

blog comments powered by Disqus