How to add *formatted* text as a DependencyProperty's type and bind it to a TextControl's content?

I have created a UserControl. Its XAML contains a TextBlock to represent a Description property displayed on the control's surface.

I need advice on how to turn this description into a dependency property of the class.

The hard part is that the description may contain formatting, such as <Underline>, <LineBreak> etc. So I can't just use a string property and bind it to the TextBlock.Text property.

What is the best data type for that property to enable this scenario

NB: I have been able to "solve" this problem crudely, and unsatisfactorily, by creating a DependencyProperty (called Description) in the codebehind class with a data type of TextBlock. The xaml for the UserControl then contains the following markup:


Answer this question

How to add *formatted* text as a DependencyProperty's type and bind it to a TextControl's content?

  • djun_kang

    Just off the top of my head:

    1. Instead of having a TextBlock inside your user control, just put a ContentControl
    2. Make your user control's dependency property type Object
    3. Bind your ContentControl's Content property to the dependency property and let it handle the rest.

    If it's a string, ContentControl will turn it into a TextBlock. If it's anything else, it should inject it into the logical tree for you as is.

    HTH,
    Drew


  • sugar1985

    Thanks, Drew. That works very nicely!

    The only slight problem remaining is that it isn't strongly typed - but I can live with that, as I will be the one instantiating the control.



  • How to add *formatted* text as a DependencyProperty's type and bind it to a TextControl's content?