Can I convert XML/XAML into WPF controls at runtime?
Is there a way to take a chunk of XML/XAML and load it as WPF controls at runtime?
Related:
Can I use XamlReader.开发者_JAVA百科Load or InitializeFromXaml from a WPF Window, for the Window definition?
yes. what you want to look at is the XamlReader class, specefically, XamlReader.Load
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);
精彩评论