2017-08-16 41 views
1

集合设置为自定义的绑定属性我有一个自定义ContentView与定义的绑定属性:Xamarin - 在XAML

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中设置一个值吗?

我想:

<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 

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

+0

我测试你的代码 - 它工作得很好!我觉得这个编译错误是由智能感知假阳性。此外,建议您更改'的IEnumerable '了'returnType'参数(在Binding.Create)为'IEnumerable的'。 – Ada

回答

1

您的内容查看更改为这样的事情:

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事件。

而且做的BindableProperty一些变化。

所以,现在在你的XAML可以添加的项目是这样的:

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

希望这helps.-

相关问题