3

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

2
  • I don't think this is possible to do in WinUI (at this point) without XAML. It is still way more limited than WPF. Commented Oct 11, 2022 at 9: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. Commented Oct 11, 2022 at 14:04

1 Answer 1

2

The only way to create a DataTemplate programmatically in WinUI 3 is to use the XamlReader.Load 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.

Sign up to request clarification or add additional context in comments.

2 Comments

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<FrameworkElement>)
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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.