1

How to create a DataTemplate in C# in a WinUI app, without having the template stored as a resource in XAML or loading from a XAML string (which is very slow)?

In WPF, it was possible using the VisualTree property, but this does not exist in WinUI.

Please note I'm already aware of this question: How to programatically create a dataContext and assign a grid to it in c# (code behind) which does not answer mine

JamesL
  • 351
  • 2
  • 10
  • I don't think this is possible to do in WinUI (at this point) without XAML. It is still way more limited than WPF. – Nick Oct 11 '22 at 09:34
  • @Nick Thanks. That's really really bad. I'm still trying to think of a way, there must be a way, even if it requires some little hacks. – JamesL Oct 11 '22 at 14:04

1 Answers1

2

The only way to create a DataTemplate programmatically in WinUI 3 is to use the XamlReader.Parse method.

It's unclear why you think this is "very slow" compared to using the VisualTree property and the FrameworkElementFactory in WPF. Less type safe and more error prone maybe but the performance shouldn't be an issue.

Besides, the documentation has long claimed that using the FrameworkElementFactory "class is a deprecated way to programmatically create templates". The recommended approach is to use the XamlReader - even in WPF.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • I really cannot use this approach, it's impossible in my case because the library I'm working on wants to give developers a way to use a delegate without returns a FrameworkElement (`Func`) – JamesL Oct 15 '22 at 08:55
  • 1
    Well, you cannot turn a `FrameworkElement` into a `DataTemplate`. A template is a template and the only way to create one programmatically is to use `XamlReader.Parse`. Take it or leave it :) – mm8 Oct 18 '22 at 19:23