2017-08-16 2 views
1

Ich habe eine benutzerdefinierte ContentView mit einer definierten bindbare Eigenschaft:Xamarin - eine Sammlung, um benutzerdefinierte bindbare Eigenschaft in XAML Einstellung

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) => 
     { 
     } 
    ); 

Wie kann ich einen Wert dieses in XAML festlegen?

Ich habe versucht:

<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> 

Aber von Zeit zu Zeit immer Fehler folgende Zusammenstellung:

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

ich etwas falsch? Gibt es einen anderen Weg?

+0

ich Ihren Code getestet - es funktioniert! Ich denke, dass dieser Kompilierungsfehler ein falsches positives von Intellisense ist. Außerdem würde ich empfehlen, das 'returnType'-Argument (in Binding.Create) zu' IEnumerable 'von' IEnumerable 'zu ändern. – Ada

Antwort

1

Ihre InhaltAlle zu so etwas wie dies ändern:

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 
    } 
} 

Ihre IEnumerable Eigenschaftsänderung für eine ObservableCollection und abonnieren für die CollectionChanged Veranstaltung.

Nehmen Sie auch einige Änderungen in der BindableProperty vor.

So, jetzt in Ihrem XAML können Sie die Einzelteile wie folgt hinzu:

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

Hope this helps.-

Verwandte Themen