Friday, January 7, 2011

Windows Phone 7 and MVVM

Before we get started I would like to mention that as a Silverlight Developer, having the opportunity to make mobile apps without a huge learning curve is great. I can use the same skills that I learn from making Silverlight web application and go mobile. Ok enough of that, let's get going. To follow along make sure you have install the free tools from App Hub.


Open up Visual Studio 2010 and create a new Windows Phone Application. For this demonstration, I keep the default and press OK. Now that we have our project setup, create two new folders and name them ViewModels and Models (note: this step is not required but best practices). Inside the Models folder create a class called ContactModel, this class will hold four properties (First Name, Last Name, Phone Number and City).



Next we need to build the UI by adding a TextBox and a TextBlock control for each property in the ContactModel class.




Ok now that we have our Model and UI ready let's build the ViewModel. Start by creating a new class called ContactViewModel inside the ViewModels folder. Inside the ContactViewModel class implement the interface INotifyPropertyChanged. INotifyPropertyChanged allows us to track changes made in our view.  Next we create a generic list property of ContactModel and add a dummy record.  Below is what the ContactViewModel looks like.




In the view or the MainPage.xaml (assuming you kept the default when you created the project) we need to connect the view with the viewmodel using data binding. First get a reference to the ViewModel folder in the  xaml markup and then set the DataContext to the ContactViewModel.




 Setting the DataContext to the ContactViewModel allows us to bind to any public property that's in the viewmodel.




That's it, here's a screenshot of the finish WP7 app.




Go Silverlight!

No comments:

Post a Comment