简体   繁体   English

什么是在WPF中自定义绑定文本的最佳方法

[英]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". 正如标题所说,我需要自定义WPF中的部分文本,例如,我有一个短语“快速的棕色狐狸跳过懒狗”,我需要加粗“棕色”这个词,或者更改背景/前景色“狐狸” As far as I know, none of the regular WPF controls support that functionality, is there any open source/free alternatives? 据我所知,没有一个常规的WPF控件支持该功能,是否有任何开源/免费替代品?

PS the control should be bindable PS控件应该是可绑定的

Thanks. 谢谢。

I depends greatly on what you want to accomplish but you could use a RichTextBox of the WPF Toolkit as suggested here . 我在很大程度上取决于你要完成什么,但你可以使用WPF工具包的一个RichTextBox的建议在这里

Or you could add the binding capability to the .Net RichTextBox as suggested here . 或者您可以按照此处的建议将绑定功能添加到.Net RichTextBox。

However, if you don't require anything so complex as a RichTextBox. 但是,如果您不需要像RichTextBox那么复杂的任何东西。 You could use a ValueConverter and change the text you are going to show to something that better fits your needs. 您可以使用ValueConverter并将要显示的文本更改为更符合您需求的文本。 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. 同样依赖于你需要的东西,你可以创建一个带有依赖属性“Text”的用户控件,并且在PropertyChanged上,你将文本分成更小的部分,然后将它们绑定在不同的“子属性”中。在用户控件中显示不同的TextBlocks(具有不同的样式)。

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 . 如果RichTextBox不是解决方案,也不是UserControl,您可以使用ValueConverter通过TextBlock.Inline完成此操作,就像这里一样。

You can use Run to decorate your text. 您可以使用Run来装饰文本。

    <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 . 此外,如果您使用的是WPF 4.0及更高版本, Microsoft已将Run的Text属性设置为依赖属性,而不是正常的CLR属性 So, you can bind with it as well. 所以,你也可以绑定它。

Refer here for Bindable Run. 请参阅此处了解Bindable Run。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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