Wpf 更改TextBlock绑定文本中子字符串的颜色

Wpf 更改TextBlock绑定文本中子字符串的颜色,wpf,styles,textblock,Wpf,Styles,Textblock,我正在将某些属性绑定到我的TextBlock: <TextBlock Text="{Binding Status}" Foreground="{Binding RealTimeStatus,Converter={my:RealTimeStatusToColorConverter}}" /> 转换器: public class RealTimeStatusToColorConverter : MarkupExtension, IValueConverte

我正在将某些属性绑定到我的
TextBlock

<TextBlock 
    Text="{Binding Status}" 
    Foreground="{Binding RealTimeStatus,Converter={my:RealTimeStatusToColorConverter}}" 
    />
转换器:

public class RealTimeStatusToColorConverter : MarkupExtension, IValueConverter
{
    // One way converter from enum RealTimeStatus to color. 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is RealTimeStatus && targetType == typeof(Brush))
        {
            switch ((RealTimeStatus)value)
            {
                case RealTimeStatus.Cancel:
                case RealTimeStatus.Stopped:
                    return Brushes.Red;

                case RealTimeStatus.Done:
                    return Brushes.White;

                case RealTimeStatus.PacketDelay:
                    return Brushes.Salmon;

                default:
                    break;
            }
        }

        return null;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public RealTimeStatusToColorConverter()
    {
    }

    // MarkupExtension implementation
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}
您可以使用,尽管设置TextBlock需要更多的工作

看一看,我发现它相当简单但全面,我从中提取了以下片段:

        <TextBlock Margin="10" TextWrapping="Wrap">
                This <Span FontWeight="Bold">is</Span> a
                <Span Background="Silver" Foreground="Maroon">TextBlock</Span>
                with <Span TextDecorations="Underline">several</Span>
                <Span FontStyle="Italic">Span</Span> elements,
                <Span Foreground="Blue">
                        using a <Bold>variety</Bold> of <Italic>styles</Italic>
                </Span>.
        </TextBlock>

这是一个
控件
有几个
跨度元素,
使用多种风格
.

这里有一个附加属性,它将任意文本解析为XAML
TextBlock
内容,包括
Run
Span
Bold
等。这具有普遍有用的优点

我建议您编写一个
ValueConverter
,用适当的标记替换
状态
文本中的数字,这样当您给它这个文本时

错误号34:猴子猫没有蛋奶糊

…它会将其转换为以下文本:

错误号34:猴子猫没有蛋奶糊

您已经知道如何进行值转换,而使用正则表达式替换文本则是一个完全不同的主题

XAML用法:

<TextBlock
    soex:TextBlockExt.XAMLText={Binding Status, Converter={my:redNumberConverter}}"
    />

这很复杂。一种方法是将状态消息分隔为多个消息,数字内容位于单独的viewmodel属性中。但那太可怕了。更纯粹的MVVM方法是为
状态
编写另一个
ValueConverter
,它将解析消息文本并动态创建具有适当属性的多个XAML
Run
实例。但这是一个相当多的工作。这听起来不错,我可以有代码示例吗?(我是新开发人员…)非常感谢你的回答,你能发布redNumberConverter代码吗?我认为这个TextBlockText类的用法也缺少了一些东西。@davidhol在用法上有什么问题?你写的ValueConverter有什么问题?它应该是微不足道的。因为我是一名新开发人员,对WPF几乎不熟悉,所以目前这个转换器对我来说并不微不足道。@davidhol通常要求别人帮助你完成你遇到的任务。当你甚至不愿意自己去写代码的时候,这里的人就会变得毫无帮助。我不明白错误号是什么:没有给猴子猫的奶油冻。方法
<TextBlock
    soex:TextBlockExt.XAMLText={Binding Status, Converter={my:redNumberConverter}}"
    />
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace StackOverflow.Examples
{
    public static class TextBlockExt
    {
        public static String GetXAMLText(TextBlock obj)
        {
            return (String)obj.GetValue(XAMLTextProperty);
        }

        public static void SetXAMLText(TextBlock obj, String value)
        {
            obj.SetValue(XAMLTextProperty, value);
        }

        /// <summary>
        /// Convert raw string from ViewModel into formatted text in a TextBlock: 
        /// 
        /// @"This <Bold>is a test <Italic>of the</Italic></Bold> text."
        /// 
        /// Text will be parsed as XAML TextBlock content. 
        /// 
        /// See WPF TextBlock documentation for full formatting. It supports spans and all kinds of things. 
        /// 
        /// </summary>
        public static readonly DependencyProperty XAMLTextProperty =
            DependencyProperty.RegisterAttached("XAMLText", typeof(String), typeof(TextBlockExt),
                                                 new PropertyMetadata("", XAMLText_PropertyChanged));

        private static void XAMLText_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is TextBlock)
            {
                var ctl = d as TextBlock;

                try
                {
                    //  XAML needs a containing tag with a default namespace. We're parsing 
                    //  TextBlock content, so make the parent a TextBlock to keep the schema happy. 
                    //  TODO: If you want any content not in the default schema, you're out of luck. 
                    var strText = String.Format(@"<TextBlock xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">{0}</TextBlock>", e.NewValue);

                    TextBlock parsedContent = System.Windows.Markup.XamlReader.Load(GenerateStreamFromString(strText)) as TextBlock;

                    //  The Inlines collection contains the structured XAML content of a TextBlock
                    ctl.Inlines.Clear();

                    //  UI elements are removed from the source collection when the new parent 
                    //  acquires them, so pass in a copy of the collection to iterate over. 
                    ctl.Inlines.AddRange(parsedContent.Inlines.ToList());
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(String.Format("Error in Ability.CAPS.WPF.UIExtensions.TextBlock.XAMLText_PropertyChanged: {0}", ex.Message));
                    throw;
                }
            }
        }

        public static Stream GenerateStreamFromString(string s)
        {
            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);
            writer.Write(s);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }
    }
}