如何使用代码创建DataTemplate?[MAUI]

3
如何使用代码创建DataTemplate?
与WPF中的VisualTree属性不同,DataTemplate没有此属性。
文档也并没有提供帮助。
虽然有IDataTemplateController,但它并不能控制任何东西。<ignorable>又是奇怪的 MAUI 时代</ignorable>。
2个回答

4
在源代码中找到了这个信息:创建视图的函数有一个构造参数。
/// <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;
});

目前在Binding中存在一个bug,您需要指定“.”,已经合并了修复。


0
请注意,您也可以使用XAML创建部分内容,并通过代码后台进行自定义。我使用它来设置类型安全的相对绑定,因为Intellisense不支持它们。
  1. 将ContentView创建为XAML并为视图内部的元素命名
    <ContentView
        xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:vms="clr-namespace:MyProject.ViewModels"
        x:Class="MyProject.Views.MyDataTemplate"
        x:DataType="vms:MyItemViewModel">

        <HorizontalStackLayout x:Name="_template" x:FieldModifier="Public">
            <Label Text="{Binding Name}" />
        </HorizontalStackLayout>
    </ContentView>
  • 在MyDataTemplate.xaml.cs中自定义视图
  • public partial class MyDataTemplate: ContentView
    {
        public MyDataTemplate()
        {
            InitializeComponent();
    
            TapGestureRecognizer tap = new();
    
            tap.SetBinding(TapGestureRecognizer.CommandProperty, new Binding(
                nameof(MyItemContainerViewModel.ShowItemCommand),
                source: new RelativeBindingSource(RelativeBindingSourceMode.FindAncestorBindingContext, typeof(MyItemContainerViewModel))
                ));
    
            tap.SetBinding(TapGestureRecognizer.CommandParameterProperty, new Binding(Binding.SelfPath));
    
            _template.GestureRecognizers.Add(tap);
        }
    }
    
    1. 给你的DataTemplate命名一个元素,例如MyItemContainerPage。
    <ContentPage
        ...
        x:Class="MyProject.Views.MyItemContainerPage"/>
        
        <CollectionView
            x:Name="_items"
            ItemsSource="{Binding Items}">
        </CollectionView>
    </ContentPage>
    
    1. 在MyItemContainerPage.xaml.cs中设置元素的ItemTemplate
    public partial class MyItemContainerPage : ContentPage
    {
        public MyItemContainerPage :
        {
            InitializeComponent();
    
            _items.ItemTemplate = new DataTemplate(() => new MyDataTemplate()._template);
        }
    }
    

    请注意,最好只在模板类的静态字段中创建一次模板,例如 public static DataTemplate Instance { get; } = new(() => new MyDataTemplate()._template); 并将 _template 设置为私有。您也可以使用 .Content 而不是 ._template

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接