Introduction
“MVVM” stands for “Model-View-ViewModel”. Model basically initialize properties, attributes whatever you say, and “ViewModel” contains all data of your application. Finally, View represents actual representation of data in your screen. Basically Data Binding works between “ViewModel” and “View “layer, “View” requests command and “ViewModel” accept it and responses to the “View”. I’m not going to the complete theoretical knowledge. I will try to give you the basic idea what “MVVM” is.
Now, let’s get crack in the best practice in this super awesome architectural model.
Creating a New Project
Firstly, open up a new project and name it “MVVMEx” or whatever you want. Now, add three folders “Models”, “ViewModels” and “Views” one by one, like this.
Figure 1
It should look exactly like the following figure 2.
Figure 2
Adding a New Page
Now, in “Views” folder right click and add a new “Blank Page”, give it a name “AutoView”.
Figure 3
Changing the Starting Page
Now one more thing we’ve to do, is changing our starting page. For that, you’ve to go “app.xaml.cs” and change this line of code,
- if (rootFrame.Content == null)
- {
-
-
-
- rootFrame.Navigate(typeof(Views.AutoView), e.Arguments);
- }
Listing 1 Because, we’ve replaced our “
MainPage.xaml” and added a new page “
AutoView.xaml”.
Adding Classes
Now, similarly right click on the “
Model” folder and add a new class named “
Auto.cs”. Again right click on the “
ViewModels” folder and add another class named “
AutoViewModel.cs”. After setup, your Solution Explorer will look like the following figure 4.
Figure 4 Now we’ll modify our “
AutoView.xaml” as follows.
Modifying “AutoView.xaml” Page
Setting up app title and information.
-
- <StackPanel Grid.Row="0" Margin="19,0,0,0">
- <TextBlock Text="Learn With BD Devs" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
- <TextBlock Text="MVVM" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
- </StackPanel>
Listing 2 Modifying main grid -
- <Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0">
- <TextBlock Height="50"
- HorizontalAlignment="Left"
- Margin="10,10,0,0"
- Name="manufacturerBlock"
- Text="{Binding manufacturer,Mode=OneWay}"
- VerticalAlignment="Top"
- Width="342" FontSize="24"/>
- <TextBlock Height="50"
- HorizontalAlignment="Left"
- Margin="10,65,0,0"
- Name="modelBlock"
- Text="{Binding model,Mode=OneWay}"
- VerticalAlignment="Top"
- Width="342" FontSize="24"/>
- <TextBlock Height="50"
- HorizontalAlignment="Left"
- Margin="10,120,0,0"
- Name="colorBlock"
- Text="{Binding color,Mode=OneWay}"
- VerticalAlignment="Top"
- Width="342" FontSize="24"/>
- <TextBlock Height="50"
- HorizontalAlignment="Left"
- Margin="10,175,0,0"
- x:Name="yearBlock"
- Text="{Binding year, Mode=OneWay}"
- VerticalAlignment="Top"
- Width="342" FontSize="24"/>
- </Grid>
Listing 3 Implementation of “BaseModel.cs” Class
Now, we’ll move to our “
Models” folder and initialize auto’s properties, but before that, we’ve to add another class name “
BaseModel.cs” in our “
Common” folder.
- public class BaseModel : INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler PropertyChanged;
-
- protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
- {
- if (object.Equals(storage, value)) return false;
- storage = value;
- this.OnPropertyChaned(propertyName);
- return true;
- }
-
- private void OnPropertyChaned(string propertyName)
- {
- var eventHandler = this.PropertyChanged;
- if (eventHandler != null)
- eventHandler(this, new PropertyChangedEventArgs(propertyName));
- }
- }
Listing 4 It’s our “
INotifyPropertyChanged” interface. As, we’ve said in best practice, you’ve make your code as much clean as you can.
Implementation of “Auto.cs” Class
Now, move back to our “
Auto.cs” class. The initialized properties are given below:
- public class Auto : BaseModel
- {
- private string _manufacturer;
- private string _model;
- private string _color;
- private int _year;
-
- public string manufacturer
- {
- get { return _manufacturer; }
-
- set { this.SetProperty(ref this._manufacturer, value); }
- }
-
- public string model
- {
- get { return _model; }
-
- set { this.SetProperty(ref this._model, value); }
- }
-
- public string color
- {
- get { return _color; }
-
- set { this.SetProperty(ref this._color, value); }
- }
-
- public int year
- {
- get { return _year; }
-
- set { this.SetProperty(ref this._year, value); }
- }
- }
Listing 5 Here, we’ve inherited all the public properties of “
BaseModel.cs” class, and fire the value of data in setter. Just simple logic of OOP (Object Oriented Programming).
Setting Up Data in “AutoViewModel.cs” Class
Now, we’ll set the data of our “
Auto” properties in “
AutoViewModel.cs” class.
- public class AutoViewModel : Auto
- {
- Auto _auto = new Auto
- {
- manufacturer = "Oldsmobile",
- model = "Cutlas Supreme",
- color = "Silver",
- year = 1988
- };
-
- public AutoViewModel()
- {
- this.manufacturer = _auto.manufacturer;
- this.model = _auto.model;
- this.color = _auto.color;
- this.year = _auto.year;
- }
- }
Listing 6 Here, we’ve used Inheritance and inherited “
Auto.cs” class like before, so that we can access all the public properties of “
Auto.cs” class.
We created a “
_auto” object of “
Auto.cs” class and initialized all the values here, and in constructor “
AutoViewModel” we make references of these properties.
Setting Up DataContext in “AutoView.xaml.cs” Class
It’s almost done. Now, to visualize the data of our “
AutoViewModel.cs” class, we have to instantiate in our “
AutoView.xaml.cs” class. To do so, change these line of code as follows.
- private AutoViewModel defaultViewModel = new AutoViewModel();
-
- public AutoView()
- {
- this.InitializeComponent();
- ...
- this.DataContext = defaultViewModel;
- }
-
- public AutoViewModel DefaultViewModel
- {
- get { return this.defaultViewModel; }
- }
Listing 7 Here, we’ve created a “
defaultViewModel” object of “
AutoViewModel.cs” class and make it the “
DataContext” of our “AutoView.xaml.cs” class in constructor. It actually retrieves all data from “
AutoViewModel” constructor and shows in “
ContentRoot” grid of “
AutoView.xaml”.
Running the Application
Now, it’s time to build our project. After you run the application, it should look exactly like the following screenshot.
Figure 5 Summary
So, that’s it. Hope you’ve understood the concept of “
MVVM” and how to implement in your project. It’s really helpful when you’ll work in big project and you’ve to handle large amount of data.
Happy coding!
You can download the full source code,
here.