Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to build a DataTemplate with only C#

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.

like image 912
codebender Avatar asked May 28 '18 18:05

codebender


2 Answers

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 the XamlReader.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.

like image 169
mm8 Avatar answered Nov 17 '22 09:11

mm8


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.

like image 22
Grx70 Avatar answered Nov 17 '22 08:11

Grx70