Xaml解析器需要一个父对象和一个Xaml名称空间,但我为TextBlocks创建了一个扩展方法来为您完成这项工作:
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
namespace SilverlightApplication1
{
static public class TextBlockExtensions
{
static public void SetInline(this TextBlock textBlock, string text)
{
var str = @"<TextBlock xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">" + text + "</TextBlock>";
TextBlock txt = (TextBlock)XamlReader.Load(str);
List<Inline> inlines = txt.Inlines.ToList();
txt.Inlines.Clear();
foreach (var inline in inlines)
{
textBlock.Inlines.Add(inline);
}
}
}
}
MyTextBlock.SetInline(str);
我对它进行了测试,对于任何正常的Xaml文本运行都可以正常工作。好好享受。