简体   繁体   中英

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?

PS the control should be bindable

Thanks.

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 .

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 :

在此输入图像描述

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.

您可以使用HTML来自定义文本..您可以在此处获取一组HTML代码...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM