MVVM on a Windows Store App
September 10, 2013 Leave a comment
I blog for a couple of reasons:
- Professionalism – to think and write about a topic at least once a week
- Marketability – when I talk to people about jobs, I can point them to my blog to see how I code (and think about coding). To me, it is much more effective and insightful than a exam or esoteric interview questions
- To keep track of stuff for me - I write stuff down so I don’t have to remember something.
That last point came back to me today. I wanted to take a break from F# so I looked at MVVM in a Windows RT application. I went to refresh my brain on MVVM so I hit up Bing and Google. All of the recent articles that I ran across talked about MVVM –as an after thought. They were all pimping MVVM helpers like relay command, frameworks like MVVMLight, and other non-core MVVM concepts. All important to be sure, but non related to MVVM.
I then hit up my own blog and sure enough – I blogged about MVVM 2 years ago when I did a Windows Phone 7 app and I could see just the MVVM in action. So then I fired up a basic Windows RT application and added 3 folders to it: Models, Views, and ViewModels.
I then added a Model like so:
- public class Person
- {
- public Int32 Id { get; set; }
- public String FirstName { get; set; }
- public String LastName { get; set; }
- }
I then added a View Model
- public class PersonViewModel: INotifyPropertyChanged
- {
- private Person _person = null;
- public event PropertyChangedEventHandler PropertyChanged;
- public PersonViewModel(Person person)
- {
- _person = person;
- }
- public Int32 Id
- {
- get { return _person.Id; }
- set
- {
- PropertyChanged(this, new PropertyChangedEventArgs("Id"));
- _person.Id = value;
- }
- }
- public String FirstName
- {
- get { return _person.FirstName; }
- set
- {
- PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
- _person.FirstName = value;
- }
- }
- public String LastName
- {
- get { return _person.LastName; }
- set
- {
- PropertyChanged(this, new PropertyChangedEventArgs("LastName"));
- _person.LastName = value;
- }
- }
- }
I then added a View like so:
and then in the code behind of the View:
- public PersonView(PersonViewModel viewModel)
- {
- InitializeComponent();
- this.mainGrid.DataContext = viewModel;
- }
Then in the main page, the ViewModel is injected into the View:
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- Person person = new Person(){Id=0,FirstName="Test",LastName="Person"};
- PersonViewModel viewModel = new PersonViewModel(person);
- PersonView view = new PersonView(viewModel);
- view.Show();
- }
- }
And we have data binding:
Now I know this is not a complete project and that many patterns are helpful (esp. the relay command one), but this is the core of making MVVM work the MSFT way: data binding and IPropertyNotifyChanged.