Implementation of MVVM architecture with example.


I have demonstrated MVVM architecture here. In this WPF MVVM application, the model will go through the View-Model classes so that it can communicate with the Views. MVVM will be useful and easy to understand in many real time scenarios.

Description- MVVM stands for Model-View-View-Model. This example demonstrates how to fetch student data through MVVM. Please follow the steps to create application based on MVVM
Step 1) Create WPF application. For hierarchy purpose create folders View , Model and ViewModel. Solution name is "MyMVVM" which is used as namespace name.
Step 2) Add class file "StudentModelBaseClass.cs" which will act base class.
Model
Step 3) Add class file "StudentModel.cs" in Model folder. StudentModel class should be derived from StudentModelBaseClass.
ViewModel
Step 4) Add class file "StudentViewModel.cs" in to ViewModel folder. StudentViewModel class should be derived from StudentModelBaseClass.
View
Step 5) In View folder, add WPF user control "StudentView.xaml"
Step 6) StudentModelBaseClass is extended INotifyPropertyChanged interface.
Put following code in StudentModelBaseClass.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace MyMVVM
{
public abstract class StudentModelBaseClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

public virtual void RaisedPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}


Step 7) Put following code in MainWindow.xaml

<Window x:Class="MyMVVM.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ContentControl x:Name="OriginalContent" Height="300" >
</ContentControl>
</Grid>
</Window>

In this step, we have added Contentcontrol in page which will be used to view contents at runtime.
Step 8) Put following code in MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MyMVVM.ViewModel;
using MyMVVM.View;

namespace MyMVVM
{
///
/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainWindow_Loaded);
}

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var view = new StudentView();
var viewModel = new StudentViewModel();

view.DataContext = viewModel;
OriginalContent.Content = view;
}

}
}

In this step, we have added "MainWindow_Loaded" as one event handler. When this event will be fired, we get DataContext for view. OriginalContent is ContentControl in MainWindow.xaml which gets binded with view with content property.

Step 9) Put following code in "StudentViewModel.cs"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyMVVM.Model;
using System.Collections.ObjectModel;

namespace MyMVVM.ViewModel
{
class StudentViewModel :StudentModelBaseClass
{
private ObservableCollection<StudentModel> _studentList = new ObservableCollection<StudentModel>();

public ObservableCollection<StudentModel> StudentList
{
get { return _studentList ; }
set
{
_studentList = value;
RaisedPropertyChanged("StudentList");

}
}

public StudentViewModel()
{
StudentList.Add(new StudentModel
{
RollNo =1,
Name="Kamal"
});

StudentList.Add ( new StudentModel
{
RollNo=2,
Name="Kala"
});
}


}
}

In this step, we have created one observable collection for student data. Listbox which is present in StudentView.xaml of view folder will be binded with StudentList. StudentViewModel() is used to add data in to StudentList. If you do not want to have hardcoded data then you can write code to fetch data from different database tables in StudentViewModel().
Step 10) Put following code in "StudentView.xaml" which is in View folder.

<UserControl x:Class="MyMVVM.View.StudentView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBlock Text="MVVM Example" Grid.Row="0">
</TextBlock>
<ListBox ItemsSource="{Binding StudentList}" Grid.Row="1" BorderBrush="Black" Background="PowderBlue" BorderThickness="2">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Margin="10">
</StackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="Auto" >
<Grid.RowDefinitions>
<RowDefinition>
</RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="StudentName:">
</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Name}">
</TextBlock>
<TextBlock Grid.Row="1" Grid.Column="0" Text="RollNo:">
</TextBlock>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding RollNo}">
</TextBlock>
<Rectangle Height="3" Grid.ColumnSpan="2" Grid.Row="3" Fill="Black">
</Rectangle>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>


In this step, we have binded Name, ID with two different textblocks.
Step 11) Put following code in "StudentModel.cs" which is in Model folder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyMVVM.Model
{
class StudentModel : StudentModelBaseClass
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
RaisedPropertyChanged("Name");
}
}
private int _rollno;
public int RollNo
{
get { return _rollno; }
set
{
_rollno = value;
RaisedPropertyChanged("RollNo");
}
}
}
}

In this step, we have created different properties for Student. For e.g Name, roll no etc. You can add your own as well.
Step 12) Execute your application and check whether you are able to view student data at runtime or not.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: