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

时间:2015-12-18 15:34:18

标签: wpf styles textblock

我将一些属性绑定到我的TextBlock

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

Status是简单文字,RealTimeStatusenum。对于每个enum值,我正在更改TextBlock Foreground颜色。

有时我的Status消息包含数字。该消息根据enum值获得适当的颜色,但我想知道是否可以更改此消息中数字的颜色,因此数字将与文本的其余部分获得不同的颜色。

编辑。

XAML

<TextBlock my:TextBlockExt.XAMLText="{Binding Status, 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;
    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用Span,但设置TextBlock需要更多的工作。

看一下this page,我发现它相当简单但很全面,我从中摘取了这个片段:

        <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>

答案 1 :(得分:0)

这是一个附加属性,可将任意文本解析为XAML TextBlock内容,包括RunSpanBold等。这具有以下优势:通常很有用。

我建议你写一个ValueConverter,用适当的标记替换Status文本中的数字,这样当你给它这个文本时......

  

第34号错误:猴子小猫没有蛋羹。

...它会将其转换为此文本:

  

错误编号&lt; Span Foreground =&#34; Red&#34;&gt; 34&lt; / span&gt;:没有蛋羹的蛋羹。

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

XAML用法:

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

如果是我,我会疯狂地将颜色变成ConverterParameter。

这是附加属性的C#:

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;
        }
    }
}