我有一个WPF RichTextBox,它是在WPF Web服务中动态构建的。此Web服务接受从第三方Silverlight RichTextBox控件的内容中提取的xaml字符串。
<Paragraph TextAlignment=\"Left\"><Run FontFamily=\"Comic Sans MS\" FontSize=\"16\" Foreground=\"#FF0000FF\" FontWeight=\"Bold\" >This text is blue and bold.</Run></Paragraph>
如何将此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?
答案 0 :(得分:7)
您可以使用XamlReader读取您的Xaml字符串并将其转换为控件:
string templateString = "<Paragraph xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" TextAlignment=\"Left\"><Run FontFamily=\"Comic Sans MS\" FontSize=\"16\" Foreground=\"#FF0000FF\" FontWeight=\"Bold\" >This text is blue and bold.</Run></Paragraph>";
StringReader stringReader = new StringReader(templateString);
XmlReader xmlReader = XmlReader.Create(stringReader);
Paragraph template = (Paragraph)XamlReader.Load(xmlReader);
请确保在模板中包含以下标记:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
HTH