Home > Software design >  ObservableCollection binding to a view control
ObservableCollection binding to a view control

Time:10-18

How can I bind ObservableCollection to a custom view?

I have added custom view to a page:

MainPage.xaml:

<ContentPage.Content>
   <vw:ResultsListView /> 
</ContentPage.Content>

Inside MainViewModel.cs there is this corresponding property:

private ObservableCollection<FertInspectionResult> _ResultsItems;
public ObservableCollection<FertInspectionResult> ResultsItems 
{ 
   get => _ResultsItems; 
   set => SetProperty(ref _ResultsItems, value); 
}

ResultListView is a simple collection view:

<ContentView.Content>

    <CollectionView ItemsSource="{Binding ResultsItems}">
        
        <CollectionView.ItemTemplate>
        <DataTemplate>
                <Label Text="{Binding SEQ}"/>
            </DataTemplate>
    </CollectionView.ItemTemplate>
    
    </CollectionView>
  
</ContentView.Content>

I know this is not correct, but I am unable to find a way to create BindableProperty it such way that CollectionView would be filled.

CodePudding user response:

You have a typo ResultsItems in xaml vs ResultItems in view model. Also if <vw:ResultsListView /> contain your collection, you should use namespace for getting collection.

CodePudding user response:

thanks for your question. You can create your bindable property for your custom control in your Xamarin.Forms Bindable Properties,just like that:

    public static readonly BindableProperty ResultsItemsSourceProperty =BindableProperty.Create("ResultsItemsSource", typeof(ObservableCollection<MyItem>), typeof(MyContentView), null);


    public ObservableCollection<MyItem> ResultsItemsSource
    {
        get => (ObservableCollection<MyItem>)GetValue(MyContentView.ResultsItemsSourceProperty);
        set => SetValue(MyContentView.ResultsItemsSourceProperty, value);
    }

Then in your MainPage.xaml, you could use your property created:

< vm:ResultListView ResultsItemsSource="{Binding ResultsItems}"  />

In your ResultListView, just setting the BindingContext of your CollectionView to your ContentView itself:

<ContentView
    ...
    x:Name="this">
<CollectionView  BindingContext="{x:Reference this}"     ItemsSource="{Binding ResultsItemsSource}">

And now you can bind ResultsItems which is generated in ViewModel to your ResultListView.

For more info, you could also refer to ContentView Demo.

  • Related