Xamarin-将集合设置为XAML中的自定义可绑定属性 [英] Xamarin - setting a collection to custom bindable property in XAML
问题描述
我有一个具有定义的可绑定属性的自定义ContentView
:
I have a custom ContentView
with a defined bindable property:
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中为此设置一个值?
How can I set a value to this in XAML?
我尝试过:
<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>
但是会不时出现编译错误:
But getting from time to time following compilation error:
error : Value cannot be null.
error : Parameter name: fieldType
我做错了什么?有其他方法吗?
I'm doing something wrong? Is there a different way?
推荐答案
将ContentView更改为以下内容:
Change your ContentView to something like this:
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
事件.
Your IEnumerable property change it for an ObservableCollection and subscribe for the CollectionChanged
event.
还对BindableProperty进行了一些更改.
Also do some changes in the BindableProperty.
因此,现在您可以在XAML中添加以下项目:
So now in your XAML you can add the items like this:
<c:MyControl>
<c:MyControl.Items>
<c:SomeItem />
<c:SomeItem />
<c:SomeItem />
<c:SomeItem />
</c:MyControl.Items>
</c:MyControl>
希望这会有所帮助.-
这篇关于Xamarin-将集合设置为XAML中的自定义可绑定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!