我正在尝试在 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 = [];
}
当我使用 BindableContext 时DogOverview
:
public partial class DogOverview : ContentView
{
public DogOverview(DogViewModel vm)
{
InitializeComponent();
BindingContext = vm;
}
}
行中有一个错误BindingContext = vm
:**System.InvalidCastException:** 'Object must implement IConvertible.'
。我检查过,这是因为我IAnimal
在 BindableProprety 中使用了它。我只想创建具有泛型类型的自定义控件并在另一个中使用它ContentPage
,这可能吗?