Setting WPF text to TextBlock

Elad picture Elad · Nov 4, 2009 · Viewed 9.5k times · Source

I know that TextBlock can present a FlowDocument, for example:

<TextBlock Name="txtFont">
     <Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run>
</TextBlock>

I would like to know how to set a FlowDocument that is stored in a variable to a TextBlock. I am looking for something like:

string text = "<Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run>"
txtFont.Text = text;

However, The result of the code above is that the XAML text is presented unparsed.


EDIT: I guess my question was not clear enough. What I'm really trying to achive is:

  1. The user input some text into a RichTextBox.
  2. The application saves the user input as FlowDocument from the RichTextBox, and serializes it to the disk.
  3. The FlowDocument is deserialized from the disk to the variable text.
  4. Now, I would like to be able to present the user text in a TextBlock.

Therefore, as far as I understand, creating a new Run object and setting the parameters manually will not solve my problem.


The problem is that serializing RichTextBox creates Section object, which I cannot add to TextBlock.Inlines. Therefore, it is not possible to set the deserialized object to TextProperty of TextBlock.

Answer

Blounty picture Blounty · Nov 4, 2009

create and add the object as below:

        Run run = new Run("Courier New 24");
        run.Foreground = new SolidColorBrush(Colors.Maroon);
        run.FontFamily = new FontFamily("Courier New");
        run.FontSize = 24;
        txtFont.Inlines.Add(run);