我可以在运行时将XML / XAML转换为WPF控件吗?

时间:2010-02-24 04:27:26

标签: wpf xaml

有没有办法在运行时将一大块XML / XAML加载为WPF控件?


  

相关:
  Can I use XamlReader.Load or InitializeFromXaml from a WPF Window, for the Window definition?

2 个答案:

答案 0 :(得分:4)

是肯定的。 你要看的是XamlReader类,特别是XamlReader.Load

答案 1 :(得分:0)

E.g:

string xaml = 
@"<DataTemplate>
    @"<TextBlock Text=""{{Binding Converter={{StaticResource templatesConverter}}, {0} }}""/>
  @"</DataTemplate>";

MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(xaml));

ParserContext context = new ParserContext();

context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");

context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");

DataTemplate datatemplate = (DataTemplate)XamlReader.Load(stream, context);