Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create DataTemplate with code? [MAUI]

How to create a DataTemplate with code?

DataTemplate does not have a VisualTree property like in WPF.

The docu doesn't help either.

There is an IDataTemplateController, but it does not control anything. <ignorable>weird MAUI times again</ignorable>.

like image 217
kux Avatar asked Sep 12 '25 08:09

kux


1 Answers

Found it in source code: There is a constructor parameter for a function which creates the view.

/// <Docs>
///   <param name="loadTemplate">A custom content generator to be called </param>
///   <summary>Creates and initializes a new instance of the <see cref="T:Microsoft.Maui.Controls.DataTemplate" /> class.</summary>
///   <remarks>To be added.</remarks>
/// </Docs>
public DataTemplate(Func<object> loadTemplate);
new DataTemplate(() => {
    var label = new Label();
    label.SetBinding(Label.TextProperty, new Binding("."));
    return label;
});

There is currently a bug in Binding and you have to specify ".", a fix is merged.

like image 99
kux Avatar answered Sep 13 '25 23:09

kux