title | page_title | description | slug | tags | position |
---|---|---|---|---|---|
Using DataTemplate in Code |
Using DataTemplate in Code |
This article shows how to get or create a DataTemplate in code using few different approaches. |
using-datatemplate-in-code |
xamlreader,parse,datatemplate,resources |
14 |
This article shows how to get or create a DataTemplate in code using few different approaches.
The most conveninent approach is to define the DataTemplate in XAML and get it in code when needed.
{{region using-datatemplate-in-code-0}} <UserControl.Resources> </UserControl.Resources> {{endregion}}
{{region using-datatemplate-in-code-1}} public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent();
DataTemplate template = (DataTemplate)this.Resources["MyDataTemplate"];
}
}
{{endregion}}
If you don't have access to XAML you can define the DataTemplate as a string and use the XamlReader.Parse static method to parse the string to a DataTemplate object.
When using this approach you need to add all the namespaces required by the elements in the DataTemplate manually in the string or the parser context.
{{region using-datatemplate-in-code-2}} var dataTemplateString = @"" + @"" + @"<telerik:RadButton Content=""Button Content"" />" + @"<TextBlock Text=""{Binding }"" />" + @"<local:MyCustomControl />" + @"" + @"";
ParserContext parserContext = new ParserContext();
// This namespace is required for all the default elements that don't require a prefix, like DataTemplate, TextBlock, StackPanel, etc.
parserContext.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
// This is the telerik namespace required by the RadButton in this case.
parserContext.XmlnsDictionary.Add("telerik", "http://schemas.telerik.com/2008/xaml/presentation");
// This is a local namespace pointing to a namespace from your application. The same approach is used for any other namespaces.
parserContext.XmlnsDictionary.Add("local", "clr-namespace:MyNamespace;assembly=MyAssemblyName");
DataTemplate template = (DataTemplate)XamlReader.Parse(dataTemplateString, parserContext);
{{endregion}}
Creating a DataTemplate in code is not as simple as creating a visual element, like аn heir of UIelement for example. To do so you will need to use the FrameworkElementFactory class. As this is the least recommended approach for creating a DataTemplate in code there won't be example for it. But, if you need to use it check the FrameworkElementFactory documentation in MSDN.
- [Introduction]({%slug introduction%})
- [Getting Started with XAML]({%slug common-faq%})