There are two general approaches to MVVM viewmodel and view creation: view-first and viewmodel-first. The first approach sees the creation of the view before the viewmodel. Conversely, in the viewmodel-first approach, it is the viewmodel that creates the view. Both approaches have their pros and cons. Viewmodel-first potentially offers complete independence from the UI, allowing an app to be executed entirely without a UI; yet it suffers from various implementation challenges. View-first is far simpler to implement when page navigation is used, as is the case in a Silverlight for Windows Phone app.
This book uses the view-first approach exclusively.
MVVM in a XAML app relies on the assignment of a viewmodel to the view’s DataContext
property. There are a number of commonly used techniques for marrying a viewmodel to its view. Some offer a high degree of flexibility at the cost of greater complexity and decreased visibility. The technique employed throughout this book, and the one I find to be adequate in most cases, has the viewmodel instantiated in the view’s constructor. In the following example a viewmodel is assigned to the view’s DataContext
property:
public partial class FooView : PhoneApplicationPage
{
public FooView()
{
InitializeComponent();
DataContext = new FooViewModel();
}
...
}
With the DataContext
set to the viewmodel, properties of the viewmodel can be used in data binding expression in the view’s XAML.
18.225.72.133