Is there a way to build a DataTemplate without using the deprecated FrameworkElementFactory
or the XamlReader.Load
method of string interpretation to code (related question) or (another related)?
DataTemplate dt = new DataTemplate();
StackPanel sp = new StackPanel();
ComboBox cellComboBox = new ComboBox() { Visibility = Visibility.Collapsed };
CheckBox cellCheckBox = new CheckBox() { Visibility = Visibility.Collapsed };
sp.Children.Add(cellComboBox);
sp.Children.Add(cellCheckBox);
// then add the stackpanel somehow?
Update: Why?
This is for a new program that may have to be supported for years. XamlReader string parsing at runtime for something that's got a constructor, methods, properties... feels kludgy. The FrameworkElementFactory
has been deprecated for several versions but has never had a real replacement.
Is there a way to build a DataTemplate with only C#
Yes, you use either the FrameworkElementFactory
or the XamlReader.Load
method to create a DataTemplate
programmatically.
...without using the deprecated
FrameworkElementFactory
or theXamlReader.Load
method?
Short answer: No.
Why would you need yet another way when there are two already? Also note that it's perfectly fine to use the FrameworkElementFactory
class if you don't want to use strings. Despite what the documentation on MSDN says, this type is not really marked as obsolete or deprecated in .NET Framework 4.7.2.
To elaborate on @mm8's answer: no, because if you inspect the FrameworkTemplate.LoadContent
method you'll find that a template is basically a wrapper that uses either a FrameworkElementFactory
or a TemplateContent
to load the contents, TemplateContent
being a utility to read XAML node stream. So these are the only two ways in which a template can operate.
Personally, of the two, I'd recommend using XAML (as a separate *.xaml file rather than a string
), because it's far more readable, but also because FrameworkElementFactory
has limited functionality, i.e. it only supports dependency properties and routed events (you cannot create a factory that would set a regular CLR property or event handler). It has one advantage over XAML though - it does support generic classes, so perhaps a mix of the two is the most proper approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With