Davita
Davita

Reputation: 9144

What is best way to customize binded text in WPF

As the title says, I need to customize part of text in WPF, for example, I have a phrase "The quick brown fox jumps over the lazy dog", I need to bold the word "brown", or change background/foreground color of "fox". As far as I know, none of the regular WPF controls support that functionality, is there any open source/free alternatives?

P.S. the control should be bindable

Thanks.

Upvotes: 0

Views: 78

Answers (3)

Dzyann
Dzyann

Reputation: 5208

I depends greatly on what you want to accomplish but you could use a RichTextBox of the WPF Toolkit as suggested here.

Or you could add the binding capability to the .Net RichTextBox as suggested here.

However, if you don't require anything so complex as a RichTextBox. You could use a ValueConverter and change the text you are going to show to something that better fits your needs. Like this example.

Also depending a lot on what you need, you could create a User Control, with a Dependency Property "Text", and on the PropertyChanged, you break the text apart in smaller pieces, and bind them in different "sub properties" that will be shown in different TextBlocks (with different Styles) inside your User Control.

Update (added the suggestion from my comment)

If RichTextBox is not a solution, and the UserControl either, you could use a ValueConverter to accomplish this with the TextBlock.Inline, like here.

Upvotes: 1

Rohit Vats
Rohit Vats

Reputation: 81253

You can use Run to decorate your text.

    <TextBlock>
        <Run>The quick </Run>
        <Run FontWeight="Bold" Background="Yellow">brown</Run>
        <Run Foreground="Red"> fox </Run>
        <Run>jumps over the lazy dog.</Run>
    </TextBlock>

Output:

enter image description here

Also if you are using WPF 4.0 and later, Microsoft have made Text property of Run as a Dependency Property instead of normal CLR property. So, you can bind with it as well.

Refer here for Bindable Run.

Upvotes: 1

Sankarann
Sankarann

Reputation: 2665

You can make use of the HTML to customize the text.. You can get a set of HTML codes here...

Upvotes: 0

Related Questions