MVVM - Binding Lists on a Single Page / How to setup MainView and ItemView Models and setup Databinding
MVVM Question for Windows Phone
Suppose you want to have multiple Lists in your View Model and have say a Pivot Form with a different ListBox in each Panel. For illustration purposes lets say we have two listboxes for People and Places in a single page but on different panels. (PeopleList and PlacesList)
How do you setup your ViewModels. Is there one MainViewModel for each list? One MainViewModel with two Lists? I'd like to be able to navigate to the appropriate detail page detail page based on their selection.
Secondly, how do you bind each listbox to a different viewmodel when the form is loaded.
My confusion is that examples seem to indicate that when a form is loaded you set context to a single "static variable" and not sure how to specify a different source of each listbox.
Below is some sample code snippets... with questions ???
DataContext = App.ViewModel ;
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
this.Items = new ObservableCollection<ItemViewModel>();
//?? can you have more than one of these?
}
//?? should I have Public MainViewModel2() with this.Items = new OC<IVM2>
//...
/// Creates and adds a few ItemViewModel objects into the Items collection.
/// </summary>
public void LoadData()
{
this.Items.Add(new ItemViewModel() { VAR1 = "X", VAR2 = "Y"}) ;
<Grid x:Name="LayoutRoot" Background="Transparent" >
<!--Pivot Control-->
<controls:Pivot x:Name="Pivot" Title="MyApp" DataContext="{Binding}" Loaded="Pivot_Loaded">
<!--Pivot item one-->
...
<!--Pivot item two-->
<controls:PivotItem Header="people">
<Grid>
<ListBox x:Name="PeopleList" Height="442" HorizontalAlignment="Left" Margin="46,68,0,0" VerticalAlignment="Top" Width="346" ItemsSource="{Binding ItemsA}" SelectionChanged="ListBox1_SelectionChanged" />
</Grid>
<!--Pivot item three-->
<controls:PivotItem Header="places">
<Grid>
<ListBox x:Name="PlacesList" Height="442" Horizont开发者_C百科alAlignment="Left" Margin="46,68,0,0" VerticalAlignment="Top" Width="346" ItemsSource="{Binding ItemsB}" SelectionChanged="ListBox2_SelectionChanged" />
</Grid>
Answers to some of the questions:
How many / which ViewModels?
You should certainly have a MainViewModel here. And then that MainViewModel has
- two properties of the types
PeopleListViewModel
andPlacesListViewModel
, or - two list-properties
ObservableCollection<PersonViewModel>
andObservableCollection<PlaceViewModel>
. Yes, you can have as many as you like but calling them ItemsA and ItemsB isn't the best choice.
In the first option, create 2 views (UserControls) to hold the lists.
In the second option, you can use an ItemsControl and a DataTemplate to show the lists.
And in general, in MVVM try to avoid SelectedItemChanged and other events. You can databind (a section of the View) to a SelectedItem property.
精彩评论