How do i add controls to datatemplates programmatically?
For Example. Below I\'ve created TextBlock and DataTemplate.
TextBlock text = new TextBlock(
Although Archedius's method works, officially it is deprecated and instead recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class like this...
public DataTemplate Create(Type type)
{
StringReader stringReader = new StringReader(
@"
<" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/>
");
XmlReader xmlReader = XmlReader.Create(stringReader);
return XamlReader.Load(xmlReader) as DataTemplate;
}
Official line taken from msdn: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory.aspx
Code example from Fredrik Hedblad's post here: Problems with XamlReader generating DataTemplate