我有一个WPF RichTextBox,它是在WPF Web服务中动态构建的.此Web服务接受从第三方Silverlight RichTextBox控件的内容中提取的xaml字符串.
This text is blue and bold.
如何将此xaml插入我的WPF RichTextBox?我有点理解FlowDocument和Paragraph和Run的概念,所以我可以使用下面的代码用文本填充WPF RichTextBox,
FlowDocument flowDocument = new FlowDocument(); Paragraph par = new Paragraph(); par.FontSize = 16; par.FontWeight = FontWeights.Bold; par.Inlines.Add(new Run("Paragraph text")); flowDocument.Blocks.Add(par); rtb.Document = flowDocument;
但我真的不想自己解析xaml来构建一个段落,因为它会变得非常复杂.有没有办法让控件知道如何解析传入的xaml?
您可以使用XamlReader读取Xaml字符串并将其转换为控件:
string templateString = ""; StringReader stringReader = new StringReader(templateString); XmlReader xmlReader = XmlReader.Create(stringReader); Paragraph template = (Paragraph)XamlReader.Load(xmlReader); This text is blue and bold.
只需确保在模板中包含以下标记:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
HTH