How do I build a DataTemplate in c# code?
Assuming that you've already set up the ItemsSource
etc for drpCreditCardNumberWpf
...
//create the data template
DataTemplate cardLayout = new DataTemplate();
cardLayout.DataType = typeof(CreditCardPayment);
//set up the stack panel
FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(StackPanel));
spFactory.Name = "myComboFactory";
spFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
//set up the card holder textblock
FrameworkElementFactory cardHolder = new FrameworkElementFactory(typeof(TextBlock));
cardHolder.SetBinding(TextBlock.TextProperty, new Binding("BillToName"));
cardHolder.SetValue(TextBlock.ToolTipProperty, "Card Holder Name");
spFactory.AppendChild(cardHolder);
//set up the card number textblock
FrameworkElementFactory cardNumber = new FrameworkElementFactory(typeof(TextBlock));
cardNumber.SetBinding(TextBlock.TextProperty, new Binding("SafeNumber"));
cardNumber.SetValue(TextBlock.ToolTipProperty, "Credit Card Number");
spFactory.AppendChild(cardNumber);
//set up the notes textblock
FrameworkElementFactory notes = new FrameworkElementFactory(typeof(TextBlock));
notes.SetBinding(TextBlock.TextProperty, new Binding("Notes"));
notes.SetValue(TextBlock.ToolTipProperty, "Notes");
spFactory.AppendChild(notes);
//set the visual tree of the data template
cardLayout.VisualTree = spFactory;
//set the item template to be our shiny new data template
drpCreditCardNumberWpf.ItemTemplate = cardLayout;
You can use the same way I have set the ToolTip
on the TextBlock
s to set other properties such as margins.
How to create a DataTemplate using C# and set child control's resources?
FrameworkElementFactory:
This class is a deprecated way to programmatically create templates, which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate; not all of the template functionality is available when you create a template using this class. The 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.
This means, you should use the XmlReader
to activate the DataTemplate
from a string:
var dataTemplateString =
@"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<ContentControl Content=""{Binding}"" Focusable=""False"">
<ContentControl.Resources>
<DataTemplate DataType=""{x:Type data:DataItem}"">
<StackPanel Orientation=""Horizontal"">
<TextBox Text=""{Binding FirstProperty}""/>
<Label Content="" - ""/>
<TextBox Text=""{Binding SecondProperty}""/>
</StackPanel>
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
</DataTemplate>";
var stringReader = new StringReader(dataTemplateString);
XmlReader xmlReader = XmlReader.Create(stringReader);
DataTemplate dataTemplate = (DataTemplate) XamlReader.Load(xmlReader);
Alternatively you can serialize an existing DataTemplate
using XamlWriter.Save()
and then actually activate it using XamlReader.Load()
(Serialization Limitations of XamlWriter.Save).
There also exists an asynchronous implementation to load XAML objects at runtime: XamlReader.LoadAsync
.
How to create DataTemplate with ItemsControl from code behind WPF
You could use the XamlReader.Parse
method to create an elements from a XAML string dynamically:
const string Xaml = "<ItemsControl ItemsSource=\"{Binding ListOfSubObjects}\">" +
" <ItemsControl.ItemsPanel>" +
" <ItemsPanelTemplate>" +
" <StackPanel Orientation=\"Vertical\"></StackPanel>" +
" </ItemsPanelTemplate>" +
" </ItemsControl.ItemsPanel>" +
" <ItemsControl.ItemTemplate>" +
" <DataTemplate>" +
" <TextBlock Text=\"{Binding SubObjectName}\"/>" +
" </DataTemplate>" +
" </ItemsControl.ItemTemplate>" +
" </ItemsControl>";
ParserContext parserContext = new ParserContext();
parserContext.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
parserContext.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
ItemsControl itemsControl = XamlReader.Parse(Xaml, parserContext) as ItemsControl;
Related Topics
Properties VS. Fields: Need Help Grasping the Uses of Properties Over Fields
Calling Function from Generated Button in Blazor
Databinding to List - See Changes of Data Source in Listbox, Combobox
Null or Default Comparison of Generic Argument in C#
Why Does Calling a Method in My Derived Class Call the Base Class Method
How to Fix "Referenced Assembly Does Not Have a Strong Name" Error
Windows Forms Splash Screen - Show a Form While Loading Main Form
Windows Phone 8.1 Universal App Terminates on Navigating Back from Second Page
External JSON Vulnerable Because of JSON.Net Typenamehandling Auto
How Does JSON Deserialization in C# Work
Format Timespan Greater Than 24 Hour
Get the Value for a Listbox Item by Index
System.Text.JSON API Is There Something Like Icontractresolver
Format an Excel Column (Or Cell) as Text in C#
How to Quickly Check If Two Data Transfer Objects Have Equal Properties in C#