常规 BindableProperty,System.InvalidCastException:“对象必须实现 IConvertible。”

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

我正在尝试在 BindableProperty 中使用具有泛型类型的自定义控件,如下所示:

public partial class Overview : ContentView
{
    public static readonly BindableProperty AnimalsProperty =
            BindableProperty.Create(nameof(AnimalsProperty), typeof(ObservableRangeCollection<IAnimal>), typeof(Overview), null);

    public ObservableRangeCollection<IAnimal> Animals
    {
        get { return (ObservableRangeCollection<IAnimal>)GetValue(AnimalsProperty); }
        set { SetValue(AnimalsProperty, value); }
    }
}
public interface IAnimal {}
public partial class Dog: ObservableObject, IAnimal {}

DogOverview xaml:

<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="DogOverview"
            >
    <Grid>
        <local:Overview
            Animals="{Binding Dogs}"
        />
    </Grid>
</ContentView>
public partial class DogViewModel: ObservableObject 
{
    [ObservableProperty]
    private ObservableRangeCollection<Dog> _dogs = [];
}

当我在

DogOverview
中使用 BindableContext 时,例如:

public partial class DogOverview : ContentView
{
    public DogOverview(DogViewModel vm)
    {
        InitializeComponent();
        BindingContext = vm;
    }
}

BindingContext = vm
行有错误:
**System.InvalidCastException:** 'Object must implement IConvertible.'
。我检查过,发生这种情况是因为我在 BindableProprety 中使用了
IAnimal
。我只想创建具有通用类型的自定义控件并在另一个
ContentPage
中使用它,这可能吗?

mvvm maui maui-community-toolkit
1个回答
0
投票

您的

BindableProperty
可能会减少为
IEnumerable<object>
IEnumerable<IAnimal
:

    public static readonly BindableProperty AnimalsProperty =
        BindableProperty.Create(nameof(AnimalsProperty), typeof(IEnumerable<IAnimal>), typeof(Overview), null);

    public IEnumerable<IAnimal> Animals
    {
        get { return (IEnumerable<IAnimal>)GetValue(AnimalsProperty); }
        set { SetValue(AnimalsProperty, value); }
    }

我可能会将

INotifyPropertyChanged
添加到您的
IAnimal
界面:

public interface IAnimal : INotifyPropertyChanged
{
}

至于

Dogs
的实现,则无需
CommunityToolkit.Mvvm
。这是因为 ObservableCollections 被分配一次,而我们所追求的是它们的 CollectionChanged 事件,即

public partial class DogViewModel: ObservableObject 
{
     public ObservableCollection<Dog> Dogs { get; } = new ();
}
© www.soinside.com 2019 - 2024. All rights reserved.