简体   繁体   中英

Binding data of multiple classes to single list view/xamarin forms

Hello how can i bind data of multiple classes to a single list view through xaml. I sucessfully bind data from single class to a lisview but when i try to bind data of more than one classes it didn't show anything in xaml.

You cant't do that 'directly'. As all UIElement controls have only one BindingContext property, you can bind only one objet at a time.

In MVVM patterns, you implement ViewModel classes to group all the needed data to display on the associated page...

So for your 'Listview', I suggest you to make a property in your ViewModel that references a new object that is simply the aggregation of all classes you want to connect to your listview.

A simple exemple:

/// Data A needed for your listview 
public class DataA { ... }

/// Data B needed for your listview 
public class DataB { ... }

///
/// You will make a property of this type into your viewModel
///
public class ListviewAggregatedData : INotifyPropertyChanged
{
    private DataA _listviewDataPart1;
    private DataB _listviewDataPart2;

    public DataA ListViewDataPart1
    {
        get => _listviewDataPart1;
        set {  _listviewDataPart1 = value; PropertyChanged?.Invoke(...); }
    }

    public DataA ListViewDataPart2
    {
        get => _listviewDataPart2;
        set {  _listviewDataPart2 = value; PropertyChanged?.Invoke(...); }
    }

    // ....
}

And in your xaml , presuming your viewModel implements a property of type ListviewAggregatedData called 'VmAggregatedDataProp', You could have something like that:

        <ListView
            BindingContext="{Binding VmAggregatedDataProp}"
            Header="{Binding ListViewDataPart1.Title}"
            ItemsSource="{Binding ListViewDataPart2.AllMyItems}"
            />

Binding names in this example must be replaced by your own properties... Tell me if it s clear...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM