这是一个附加属性,它将任意文本解析为 XAMLTextBlock
内容,包括Run
, Span
, Bold
等等。这具有普遍有用的优点。
我建议你写一个ValueConverter
它取代了你的数字Status
带有适当标记的文本,这样当你给它这个文本时......
错误号 34:没有给猴子猫吃蛋奶冻。
...它将把它转换成这样的文本:
错误号 34:没有给小猴子吃蛋奶冻。
您已经知道如何进行值转换器,并且使用正则表达式进行文本替换完全是另一个主题。
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;
}
}
}