使用 vustom ContentView 控件时绑定数据上下文更改

问题描述 投票:0回答:1

我有以下代码:

<ListView ItemsSource="{Binding Creature.FriendlyEnvironment}"
          x:DataType="vm:PlantDetailsViewModel">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="{Binding Name}" x:DataType="m:Creature" />
                <!--<v:ListviewItemView Creature="{Binding .}" x:DataType="m:Creature" />-->
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

当我执行此代码时,标签具有正确的数据上下文,并且我可以使用“创建名称”属性。 但如果我想使用注释掉的代码,我得到以下错误:

“GardenerMaster.Views.ListviewItemView”无法转换为“GardenerMaster.Models.Creature”类型

你能帮我吗,我怎样才能将当前项目传递到我的ListviewItemView?

ListviewItemView.xaml.cs

public partial class ListviewItemView : ContentView
{
    public static readonly BindableProperty CreatureProperty =
        BindableProperty.Create(propertyName: nameof(Creature), returnType: typeof(Creature), declaringType: typeof(ListviewItemView), defaultValue: default(Creature));

    public Creature Creature
    {
        get => (Creature)GetValue(CreatureProperty);
        set => SetValue(CreatureProperty, value);
    }

    public ListviewItemView()
    {
        InitializeComponent();
    }
}

ListviewItemView.xaml

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="GardenerMaster.Views.ListviewItemView"
    x:DataType="v:ListviewItemView">
    <Label Text="{Binding Creature.Name}" />
</ContentView>

我尝试了各种方法来传递当前项目,但都不起作用。

<v:ListviewItemView Creature="{Binding}" x:DataType="m:Creature" />
<v:ListviewItemView Creature="{Binding .}" x:DataType="m:Creature" />
<v:ListviewItemView Creature="{Binding Path=.}" x:DataType="m:Creature" />

我也尝试为DataTemplate设置

x:DataType="m:Creature"
,但它也不起作用。

xaml binding maui datacontext compiled-bindings
1个回答
0
投票

您在编译的绑定中混淆了不同的数据类型。

您应该在

x:DataType
上声明
DataTemplate

<DataTemplate x:DataType="m:Creature">
    <ViewCell>
        <v:ListviewItemView Creature="{Binding .}" />
    </ViewCell>
</DataTemplate>

并确保在

ListviewItemView
:

上使用相同的声明
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:m="clr-namespace:GardenerMaster.Models"
    x:Class="GardenerMaster.Views.ListviewItemView"
    x:DataType="m:Creature">
    <Label Text="{Binding Name}" />
</ContentView>
© www.soinside.com 2019 - 2024. All rights reserved.