Reputation: 39
I have two listviews on a single Content page therefore l would like for each listview to have its own viewmodel as itemsoruce.
Upvotes: 2
Views: 4065
Reputation: 1684
Adding separate ItemsSource for ListView is easier. If this is what you are looking for. It can be done with two properties in your MainViewModel.
XAMl
<ListView
ItemsSource="{Binding ListSource1}">
</ListView>
<ListView
Grid.Column="1"
ItemsSource="{Binding ListSource2}">
</ListView>
ViewModel class
public class MainViewModel
{
public ObservableCollection<string> ListSource1 { get; set; }
public ObservableCollection<string> ListSource2 { get; set; }
public MainViewModel()
{
ListSource1 = new ObservableCollection<string>()
{
"I'm from first viewmodel",
"I'm from first viewmodel",
"I'm from first viewmodel",
"I'm from first viewmodel",
"I'm from first viewmodel",
"I'm from first viewmodel"
};
ListSource2 = new ObservableCollection<string>()
{
"I'm from second ViewModel",
"I'm from second ViewModel",
"I'm from second ViewModel",
"I'm from second ViewModel",
"I'm from second ViewModel",
"I'm from second ViewModel"
};
}
}
If you are looking to add source from different ViewModels.
ListSource1 = new ViewModel1().ListSource;
ListSource2 = new ViewModel2().ListSource;
If you wish to set BindingContext of ListView this can be done by binding the Binding Context itself as Marco suggests.
But you need to add the ViewModels as well to you main ViewModel as properties.
public ViewModel1 FirstViewModel { get; set; }
public ViewModel2 SecondViewModel { get; set; }
Xaml:
<ListView
BindingContext="{Binding FirstViewModel}"
Upvotes: 2
Reputation: 1093
Just set your BindingContext for your ListView.
In Xaml:
<ListView x:Name="list1">
</ListView>
<ListView x:Name="list2">
</ListView>
And in Code behind just bind it:
list1.BindingContext = ViewModel1;
list2.BindingContext = ViewModel2;
If you whish to bind it in code behind, you could use the BindingContext-Property in XAML too:
<ListView ItemSource="{Binding itemList1}" BindingContext="{Binding ViewModel1}" />
<ListView ItemSource="{Binding itemList2}" BindingContext="{Binding ViewModel2}" />
But keep in mind, that you need a "global" binding Model (or MasterViewModel) which keeps the nested View Models as child properties.
Upvotes: 1