Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting WPF text to TextBlock

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.

like image 766
Elad Avatar asked Nov 04 '09 11:11

Elad


2 Answers

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);
like image 120
Blounty Avatar answered Nov 03 '22 22:11

Blounty


I know that TextBlock can present FlowDocument

What makes you think that ? I don't think it's true... The content of a TextBlock is the Inlines property, which is an InlineCollection. So it can only contain Inlines... But in a FlowDocument, the content is the Blocks property, which contains instances of Block. And a Block is not an Inline

like image 32
Thomas Levesque Avatar answered Nov 03 '22 23:11

Thomas Levesque