Join Tim Heuer and Craig Shoemaker to learn to build a simple quiz application using Model-View-ViewModel in Silverlight.
Download code sample: mvvm-sl.zip
Duration: 1 hour
@Todd:
When i change the DataContext of the view to the viewmodel object, the exception no longer fires when i click the button but the questions no longer appear in the ItemsControl. All that gets displayed is the button.
Do i need to change the bindings for the UI elements or should this just work?
Thanks
Robbie
Actually, there are a few changes that should be made. You really don't want to create a new instance of the QuestionViewModel in your view. So the original code in the button click event works if you make a different change. You really want to set the DataContext differently.
void Page_Loaded(object sender, RoutedEventArgs e)
{
QuestionViewModel qdata = new QuestionViewModel();
qdata.FetchQuestions();
QuestionDataView.DataContext = qdata;
}
Notice the change to set the DataContext to the actual View. Now change the View's XAML to set the ItemsSource property of the ListView.
<ItemsControl ItemsSource="{Binding Questions}">
This way, you have bound the actual ViewModel to the DataContext of your View and you can access any of the properties of your ViewModel in the View.
Hopefully that makes sense.
That didn't work either.
Changed as follows to make it work:
private void Button_Click(object sender, RoutedEventArgs e)
ObservableCollection<PMPSample.Model.Question> q = this.DataContext as ObservableCollection<PMPSample.Model.Question>;
QuestionViewModel vminst = new QuestionViewModel();
vminst.Questions = q;
vminst.SubmitAnswers();
Namespace added System.Collections.ObjectModel
@rubans: Button click code is trying to set data to ViewModel instead of ViewModel.Questions. Changed as below to get it working.
//var data = this.DataContext as QuestionViewModel;
//data.SubmitAnswers();
vminst.Questions = this.DataContext as ObservableCollection<PMPSample.Model.Question>;
It doesn't seem to work for me when Click on the submit button, get a Object reference not set to an instance of an object.