MVVM Structure
This post explains how to set up a project according to the MVVM Design Pattern (Model-View-ViewModel). What needs to be done is to create three projects called Model
(WCF Service Application), View
(Silverlight application), and ViewModel
(Silverlight class):
Step 1: Add a new project named Model
: Right-click on your Solution >> Add new project >> Visual C# >> WCF >> WCF Service Application. The project will contain the method that connects to the database and returns a list. OBS: Remember to change to .Net Framework 3.5 instead of .NET Framework 4.0.
Step 2: Add a new project named View. Right-click on your Solution >> Add new project >> Visual C# >> Silverlight >> Silverlight Application. This project will contain all the .xaml files.
Uncheck the "Host the Silverlight application in a new or existing Web site in the solution".
Step 3: Add a new project named ViewModel. Right-click on your Solution >> Add new project >> Visual C# >> Silverlight >> Silverlight Class Library. A class will be auto-generated, and name it MainPage_ViewModel.cs
as it will contain all code-behind for your MainPage.xaml
.
So, the structure of the application has been created, and next we need to link the View
and ViewModel
together, by creating a reference:
Step 4: Select your View
and right-click on References
: Click Add reference >> Projects >> Chose ViewModel
from the list.
Step 5: Go to MainPage.xaml.cs
, and add using ViewModel;
at the top. Also, add the code snippet seen in line 8, that will create a new instance of the MainPage_ViewModel()
class.
using ViewModel; namespace View { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); this.DataContext = new MainPage_ViewModel(); } } }
And that's it! (Well, almost: to actually use this structure and gather data from a database thorugh a WCF and bind the Model
and the ModelView
together, you'll need to follow the steps of my next post).
Leave a comment