请注意,您也可以使用XAML创建部分内容,并通过代码后台进行自定义。我使用它来设置类型安全的相对绑定,因为Intellisense不支持它们。
- 将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);
}
}
- 给你的DataTemplate命名一个元素,例如MyItemContainerPage。
<ContentPage
...
x:Class="MyProject.Views.MyItemContainerPage"/>
<CollectionView
x:Name="_items"
ItemsSource="{Binding Items}">
</CollectionView>
</ContentPage>
- 在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
。