我可以动态地将TextBlock.Text的一部分设置为不同的颜色吗?

4

我在主窗体中有一个TextBlock。在应用程序运行期间,我将Text属性设置为不同的字符串。

我希望能够着色特定字符串的部分。

伪代码:

if(a < 0) txbStatus.Text = string.Format("{0} <RED>{1}</RED>",  a, b);
     else txbStatus.Text = string.Format("{0} <BLUE>{1}</RED>", a, b);

你能不能也使用RichTextBlock,就像这个链接中的https://dev59.com/rnI-5IYBdhLWcg3wSGUB#1926822那样? - Ehtesh Choudhury
3个回答

12

你可以按你想要的方式拆分字符串,然后使用foreach()循环来尝试遍历该拆分后的字符串

TextBlockName.Inlines.Add(new Run("colored text") {Foreground = Brushes.Blue});

1
运行完美。谢谢!(不过有一个多余的括号) - Boppity Bop
多余的括号现在已经删除。 - Marcel Gosselin

7
TextBox 的内容不仅可以是字符串,还可以是一组 Inline 元素。
txbStatus.Inlines.Clear();
txbStatus.Inlines.Add(new Run("normal color, "));
txbStatus.Inlines.Add(new Run("colored text") { Foreground = Brushes.Red });

3
我创建了一个自定义的TextBlock,可以帮助您在TextBlock的“Text”值中突出显示一些文本部分。
using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;

    namespace UI.WPF.UserControls
    {
        class CustomTextBlock:TextBlock
        {
            string _originalText;

            public string HighlighText
            {
                get { return (string)GetValue(HighlighTextProperty); }
                set
                {
                    SetValue(HighlighTextProperty, value);

                    RenderHighlightedText();
                }
            }

            // Using a DependencyProperty as the backing store for HighlighText.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty HighlighTextProperty =
                DependencyProperty.Register("HighlighText", typeof(string), typeof(CustomTextBlock),
                     new FrameworkPropertyMetadata(new PropertyChangedCallback(HighlighTextProperty_Changed))
                     );

            private static void HighlighTextProperty_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                CustomTextBlock textBlock = (CustomTextBlock)d;
                textBlock.RenderHighlightedText();
            }


            public CustomTextBlock()
                : base()
            {

            }

            static CustomTextBlock()
            {
                DefaultStyleKeyProperty.OverrideMetadata(
                    typeof(CustomTextBlock),
                    new FrameworkPropertyMetadata(typeof(CustomTextBlock)));
            }

            public override void OnApplyTemplate()
            {

                base.OnApplyTemplate();
            }

            protected override void OnInitialized(EventArgs e)
            {
                base.OnInitialized(e);
                _originalText = Text;

                RenderHighlightedText();
            }


            private Run GetFormatedText(string text, bool isBold)
            {
                Run noramlRun = new Run(text);
                if (isBold)
                {
                    noramlRun.FontWeight = FontWeights.Bold;
                }
                else
                {
                    noramlRun.FontWeight = FontWeights.Normal;
                }

                return noramlRun;
            }
            public void RenderHighlightedText()
            {
                var boldText = HighlighText;

                if (!string.IsNullOrEmpty(HighlighText) &&
                    _originalText.ToLower().Contains(boldText.ToLower()))
                {

                    this.Inlines.Clear();

                    int point = _originalText.ToLower().IndexOf(boldText.ToLower());
                    string strHighlighted = _originalText.Substring(point, HighlighText.Length);

                    Run runHighlight = GetFormatedText(strHighlighted, true);

                    if (point == 0)
                    {
                        this.Inlines.Add(runHighlight);
                        int remainingLength = _originalText.Length - (point + HighlighText.Length);

                        string remaingText = _originalText.Substring((point + HighlighText.Length), remainingLength);
                        this.Inlines.Add(GetFormatedText(remaingText, false));
                    }
                    else
                    {
                        string firstPart = _originalText.Substring(0, point);
                        this.Inlines.Add(GetFormatedText(firstPart, false));
                        this.Inlines.Add(runHighlight);
                        int remainingLength = _originalText.Length - (point + HighlighText.Length);
                        string remaingText = _originalText.Substring((point + HighlighText.Length), remainingLength);
                        this.Inlines.Add(GetFormatedText(remaingText, false));

                    }

                }
                else
                {

                    this.Inlines.Clear();


                    this.Inlines.Add(GetFormatedText(_originalText, false));
                }

            }
        }
    }

如何使用它。
                <usercontrol:CustomTextBlock Text="{Binding Title}" 
                                    HighlighText="{Binding DataContext.SearchText, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Page}}}" 

                                   />

更多信息请访问:

https://sites.google.com/site/greateindiaclub/mobil-apps/windows8/highlightpartoftextinwpftextblockcontrol


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接