I am binding some property into my TextBlock
:
<TextBlock
Text="{Binding Status}"
Foreground="{Binding RealTimeStatus,Converter={my:RealTimeStatusToColorConverter}}"
/>
Status
is simple text and RealTimeStatus
is enum
. For each enum
value I am changing my TextBlock
Foreground
color.
Sometimes my Status
message contains numbers. That message gets the appropriate color according to the enum
value, but I wonder if I can change the colors of the numbers inside this message, so the numbers will get different color from the rest of the text.
Edit.
XAML
<TextBlock my:TextBlockExt.XAMLText="{Binding Status, Converter={my:RealTimeStatusToColorConverter}}"/>
Converter:
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;
}
}
You can use the Span, although it will take a bit more work to set up your TextBlock.
Take a look at this page, which I find to be fairly simple but comprehensive, and from which I've pulled this snippet:
Here's an attached property which parses arbitrary text as XAML
TextBlock
content, includingRun
,Span
,Bold
, etc. This has the advantage of being generally useful.I recommend you write a
ValueConverter
which replaces the numbers in yourStatus
text with appropriate markup, such that when you give it this text......it would convert that into this text:
You already know how to do value converters, and text substitution with regular expressions is a different subject entirely.
XAML usage:
If it were me I'd go hog wild and make the color a ConverterParameter.
Here's the C# for that attached property: