Xamarin - 在 XAML 中将集合设置为自定义可绑定属性

2024-03-26

我有一个习惯ContentView具有定义的可绑定属性:

    public IEnumerable<SomeItem> Items
    {
        get => (IEnumerable<SomeItem>)GetValue(ItemsProperty);
        set => SetValue(ItemsProperty, value);
    }

    public static readonly BindableProperty ItemsProperty = BindableProperty.Create(
        nameof(Items),
        typeof(IEnumerable<SomeItem>),
        typeof(MyControl),
        propertyChanged: (bObj, oldValue, newValue) =>
        {
        }
    );

如何在 XAML 中为此设置值?

I tried:

<c:MyControl>
   <c:MyControl.Items>
      <x:Array Type="{x:Type c:SomeItem}">
           <c:SomeItem />
           <c:SomeItem />
           <c:SomeItem />
      </x:Array>
   </c:MyControl.Items>
</c:MyControl>

但时不时会出现以下编译错误:

error : Value cannot be null.
error : Parameter name: fieldType

我做错了什么吗?有不同的方法吗?


将您的 ContentView 更改为如下所示:

public partial class MyControl : ContentView
{
    public ObservableCollection<SomeItem> Items { get; } = new ObservableCollection<SomeItem>();

    public MyControl()
    {
        InitializeComponent();

        Items.CollectionChanged += Items_CollectionChanged;
    }

    public static readonly BindableProperty ItemsProperty = BindableProperty.Create(
        nameof(Items),
        typeof(ObservableCollection<SomeItem>),
        typeof(MyControl)
    );

    void Items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
       //Here do what you need to do when the collection change
    }
}

您的 IEnumerable 属性将其更改为 ObservableCollection 并订阅CollectionChanged event.

还要对 BindableProperty 进行一些更改。

现在,您可以在 XAML 中添加如下项目:

<c:MyControl>
   <c:MyControl.Items>
        <c:SomeItem />
        <c:SomeItem />
        <c:SomeItem />
        <c:SomeItem />
    </c:MyControl.Items> 
</c:MyControl>

希望这可以帮助。-

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Xamarin - 在 XAML 中将集合设置为自定义可绑定属性 的相关文章

随机推荐