Hi im learning about MVVM and Win8 app development, and Im having trouble with binding an ObservableCollection (located in NoteViewModel.cs) to my MainPage listbox (or listview) through XAML.
public ObservableCollection<Note> NotesList;
The Model is a simple Note.cs class, which holds NoteText, Priority and RemindDate.
What Im doing right now is set the DataContext in the code-behind file of MainPage.xaml.cs
to the ObservableCollection.
public MainPage()
{
this.InitializeComponent();
NoteViewModel nvm = new NoteViewModel();
noteListView.DataContext = nvm.NotesList;
}
And in the NoteViewModel Constructor I simply create 2 new Notes which I then add to the Collection.
What I would like to do is set the DataContext in XAML to the NoteViewModel and the ItemsSource to the NotesList. I want to implement a DetailsView to a single note later.
There are lots of tutorial with binding collections to listboxes,
but I havent found one which shows the MVVM-correct way to do so.
Any help?
You need to bind your View (MainPage) to your ViewModel, rather than setting the DataContext of your list to the collection
Then in your view’s xaml, you bind the list’s ItemSource to your ViewModels NotesList property
E.G.
ViewModel:
You can still set the DataContext in code behind if you wish
Alternatively you can set the DataContext via your View’s xaml. Assuming your ViewModel is in the namespace MyProject:
Add a reference to your namespace
Add the ViewModel as a resource
Bind your main container’s DataContext to this resource
After you have set the DataContext, you then need to set the ItemSource for the notesListView control via a binding