Implementing M-V-VM pattern in WPF
March 16th, 2009 § Leave a Comment
- Model-View-ViewModel is a design pattern used to create client applications that take advantage of data-binding in WPF
- View = Thing you see on the screen that the user interacts with
- View-Model = something that the view binds to/ the visual state of the data
- Model = your data object
- Interaction between the view and the view-model is done by data binding
- Things to know before approaching this pattern:
- Become familiar with XAML including data-binding and use of commands
- Workflow
- Consider how the view is going to bind to the View-Model
- What properties are expected?
- Create the view and identify the properties required for binding
- Create the view-model that exposes the properties required by the view
- Consider how the view is going to bind to the View-Model
- Building a View-Model
- Consider building presentation friendly adapter around the model object
- Think about taking a view and creating a VM that stores the state of the view
- When you build a VM, pass in the model (data model) to the constructor so that you can easily connect and use the model from within the VM
- VM is just an adapter or a wrapper class where it is wrapping the original model, wrapping can be done in the constructor or using the lazy load method i.e. on property getters
- VMs can also be used to wrap other VMs
- Set the VM as the data context of the view
- Add state properties to the VM as required
- Consider defining interface for the VM so that the contract between the View and the VM is well defined
- Instead of using click handler use command binding. This will make unit testing easier as commands are exposed by the VM. Command in WPF implement ICommand interface
- Files you might end up with:
- SomeView.xaml
- ISomeViewModel.cs
- SomeViewModel.cs
- ISomeModel.cs
- SomeModel.cs