Splinter - WPF MVVM Framework

by iFour Technolab Pvt. Ltd. / Friday ,27th November 2020 / Published in WPF, WPF Development, Splinter, MVVM Framework

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

What is MVVM Framework in WPF?

MVVM(Model-View-ViewModel) is a software architecture design pattern that will allow you to utilize the Model-View-ViewModel design pattern in the WPF application. The MVVM is a design pattern that will divide your application into three layers (Model, View, ViewModel).

  1. Model: Here we can define business logic and data. The model can represent the actual data or information (like name, contact, address, phone number, date of birth, etc.).
  2. View: In, view we can set UI using the visual elements like labels, buttons, editors, etc., and bind it with View Model.
  3. ViewModel: Here we can define the logic that connects the View and the Model. For managing a list of contacts view model is designed.

Here we depict significant features of MVVM Framework.

  1. ViewModel: These classes are used for implementing validation, consuming service, commands, bindable properties, and interaction between View Models.
  2. Services: We can define all the services in View and we can use their functionality in View Models.
  3. Commands: We can bind the Commands in the View and define their action in View Model.
  4. DXBinding: The Binding can extend with the DXCommand, DXEvent, and DXBinding markup extensions.
  5. MIF: MIF stands for Module Injection Framework. This is a collection of classes. That can allow you to organize an MVVM application.
  6. Behaviors: We can extend the functionality of visual control and comply with the MVVM pattern.

For developing a simple application, MVVM can provide some components.

  1. ViewLocator: Enable you to locate views by their type name.
  2. Messenger: Allow you to exchange the message between modules.
  3. Converters: Allow you to perform conversions between different types and between the value of the same type.
  4. Data Annotation Attributes Support: These attributes can be used to customize data classes. Data annotation attributes can define validation rules, set relationships between data classes, and specify how data is displayed from a data source.
  5. Weak Event: Weak event can implement interaction between different application modules (like data services and view models) and objects.
  6. LayoutTreeHelper: LayoutTreeHelper can provide an API. And this API is used for searching nodes and iterating through elements of logical and visual trees.


Building Block of MVVM Architecture

ICommand: ICommand is used to control the behavior such as enable, disable of control behavior on execution. ICommand interface can also provide the code contract for the commanding behavior of Runtime XAML.

INotifyPropertyChanged: This interface can define when the value of a property change. It can be raised PropertyChanged event when the value changes.

Binding to Property: Below components are used for data binding as it helps to present data in the view. Their four-component for data binding.

  1. Binding target object
  2. Target property
  3. Binding source
  4. Path of the value in the binding source to use

We can set data flow in four ways.

  1. OneWay
  2. TwoWay
  3. OneWayToSource
  4. OneTime

Let’s see a simple example of MVVM Framework. Here we can add the Student details.


Step: 1

First create a WPF application, after successful creation of the application create a three folder in the root application and the name should be View, Model, and ViewModel.


Step: 2

Add a new class in the Model folder. For add new class, Right-click of the Model folder -> Add -> Class -> Add class name and press OK.

After adding a class create their properties, here the Student is our class name let’s see below code.

In this example we can add Student details like FirstName and LastName for this here we can add two properties FirstName and LastName.


using System.ComponentModel.DataAnnotations;

namespace WPFMVVMFramework.Model
{
    public class StudentData
    {
        [Key]
        public int StudentNumber{ get; set; }
        public string StudentFirstOrLastName{ get; set; }
        public string StudentCast{ get; set; }
    }
}



Step: 3

After that create one more class for DbContext. DbContext is used to write and execute the queries, bind objects in memory to UI controls.

using System.Data.Entity;

namespace WPFMVVMFramework.Model
{
    public class Contextdb : DbContext
    {
        public Contextdb() : base("Conn")
        {

        }
        public DbSet<StudentData> Studentinformation { get; set; }
    }
}


Step: 4

Now, create a ViewModel, right-click on the ViewModel folder and add a new class.

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WPFMVVMFramework.Model;

namespace WPFMVVMFramework.ViewModel
{
    public class AddDataViewModel : ViewModelBase
    {
        public AddDataViewModel()
        {
            DataList = new ObservableCollection<StudentData>(contextdb.Studentinformation);
        }

        private StudentData _studentObj = new StudentData();

        public StudentData StudentObj
        {
            get 
            { 
                return _studentObj; 
            }
            set 
            { 
                _studentObj = value; 
                RaisePropertyChanged(); 
            }
        }

        public ICommand Userlist => new RelayCommand(adddata1);
        public Contextdb contextdb = new Contextdb();
        public ObservableCollection<StudentData> _dataList;
        public ObservableCollection<StudentData> DataList
        {
            get 
            { 
                return _dataList; 
            }
            set 
            { 
                _dataList = value; 
                RaisePropertyChanged(); 
            }
        }
        private void adddata1()
        {
            contextdb.Studentinformation.Add(_studentObj);
            contextdb.SaveChanges();
            MessageBox.Show("Insert Successfully.....");
            DataList = new ObservableCollection<StudentData>(contextdb.Studentinformation);


        }
    }
}

Here, is the code to add student data. In this ViewModel, we can add ObservableCollection for a list of student data, add their properties, and add MessageBox for showing the success message.


Step: 5

Now, we create a design for adding Student data.

<xmp>
<Window x:Class="WPFMVVMFramework.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFMVVMFramework"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="50"/>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock Text="FirstName" Grid.Column="0" Grid.Row="0"/>
        <TextBox Grid.Column="1" Grid.Row="0" Text="{Binding Path=StudentObj.StudentFirstOrLastName}"/>
        <TextBlock Text="LastName" Grid.Column="0" Grid.Row="1" />
        <TextBox Grid.Column="1" Grid.Row="1" Text="{Binding Path=StudentObj.StudentCast}"/>
        <Button Content="Add" Grid.Column="0" Grid.Row="2" Height="30" Width="50" Command="{Binding Userlist}">

        </Button>
        <DataGrid AutoGenerateColumns="False" x:Name="datagrid1" ItemsSource="{Binding DataList}" Grid.Column="0" Grid.Row="3" Background="LightGray" RowBackground="LightYellow" AlternatingRowBackground="LightBlue" BorderThickness="5">
            <DataGrid.Columns>
                <DataGridTextColumn Header="FirstName" Binding="{Binding StudentFirstOrLastName}"/>
                <DataGridTextColumn Header="LastName" Binding="{Binding StudentCast}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

</xmp>

Here, we can bind the View with the ViewModel. In this view, we can use the grid for adding data and DataGrid for showing data.


Output:

Image: Fill the data

Image: Success Message

Image: Data Added Successfully

Conclusion

The prior advantage of using MVVM Framework is to provide a clear separation between business logic and presentation. Using MVVM Framework we can accelerate speed and performance enhancements.

What is MVVM Framework in WPF?

MVVM(Model-View-ViewModel) is a software architecture design pattern that will allow you to utilize the Model-View-ViewModel design pattern in the WPF application. The MVVM is a design pattern that will divide your application into three layers (Model, View, ViewModel).

  1. Model: Here we can define business logic and data. The model can represent the actual data or information (like name, contact, address, phone number, date of birth, etc.).
  2. View: In, view we can set UI using the visual elements like labels, buttons, editors, etc., and bind it with View Model.
  3. ViewModel: Here we can define the logic that connects the View and the Model. For managing a list of contacts view model is designed.

Here we depict significant features of MVVM Framework.

  1. ViewModel: These classes are used for implementing validation, consuming service, commands, bindable properties, and interaction between View Models.
  2. Services: We can define all the services in View and we can use their functionality in View Models.
  3. Commands: We can bind the Commands in the View and define their action in View Model.
  4. DXBinding: The Binding can extend with the DXCommand, DXEvent, and DXBinding markup extensions.
  5. MIF: MIF stands for Module Injection Framework. This is a collection of classes. That can allow you to organize an MVVM application.
  6. Behaviors: We can extend the functionality of visual control and comply with the MVVM pattern.

For developing a simple application, MVVM can provide some components.

  1. ViewLocator: Enable you to locate views by their type name.
  2. Messenger: Allow you to exchange the message between modules.
  3. Converters: Allow you to perform conversions between different types and between the value of the same type.
  4. Data Annotation Attributes Support: These attributes can be used to customize data classes. Data annotation attributes can define validation rules, set relationships between data classes, and specify how data is displayed from a data source.
  5. Weak Event: Weak event can implement interaction between different application modules (like data services and view models) and objects.
  6. LayoutTreeHelper: LayoutTreeHelper can provide an API. And this API is used for searching nodes and iterating through elements of logical and visual trees.


Building Block of MVVM Architecture

ICommand: ICommand is used to control the behavior such as enable, disable of control behavior on execution. ICommand interface can also provide the code contract for the commanding behavior of Runtime XAML.

INotifyPropertyChanged: This interface can define when the value of a property change. It can be raised PropertyChanged event when the value changes.

Binding to Property: Below components are used for data binding as it helps to present data in the view. Their four-component for data binding.

  1. Binding target object
  2. Target property
  3. Binding source
  4. Path of the value in the binding source to use

We can set data flow in four ways.

  1. OneWay
  2. TwoWay
  3. OneWayToSource
  4. OneTime

Let’s see a simple example of MVVM Framework. Here we can add the Student details.


Step: 1

First create a WPF application, after successful creation of the application create a three folder in the root application and the name should be View, Model, and ViewModel.


Step: 2

Add a new class in the Model folder. For add new class, Right-click of the Model folder -> Add -> Class -> Add class name and press OK.

After adding a class create their properties, here the Student is our class name let’s see below code.

In this example we can add Student details like FirstName and LastName for this here we can add two properties FirstName and LastName.


using System.ComponentModel.DataAnnotations;

namespace WPFMVVMFramework.Model
{
    public class StudentData
    {
        [Key]
        public int StudentNumber{ get; set; }
        public string StudentFirstOrLastName{ get; set; }
        public string StudentCast{ get; set; }
    }
}



Step: 3

After that create one more class for DbContext. DbContext is used to write and execute the queries, bind objects in memory to UI controls.

using System.Data.Entity;

namespace WPFMVVMFramework.Model
{
    public class Contextdb : DbContext
    {
        public Contextdb() : base("Conn")
        {

        }
        public DbSet<StudentData> Studentinformation { get; set; }
    }
}


Step: 4

Now, create a ViewModel, right-click on the ViewModel folder and add a new class.

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WPFMVVMFramework.Model;

namespace WPFMVVMFramework.ViewModel
{
    public class AddDataViewModel : ViewModelBase
    {
        public AddDataViewModel()
        {
            DataList = new ObservableCollection<StudentData>(contextdb.Studentinformation);
        }

        private StudentData _studentObj = new StudentData();

        public StudentData StudentObj
        {
            get 
            { 
                return _studentObj; 
            }
            set 
            { 
                _studentObj = value; 
                RaisePropertyChanged(); 
            }
        }

        public ICommand Userlist => new RelayCommand(adddata1);
        public Contextdb contextdb = new Contextdb();
        public ObservableCollection<StudentData> _dataList;
        public ObservableCollection<StudentData> DataList
        {
            get 
            { 
                return _dataList; 
            }
            set 
            { 
                _dataList = value; 
                RaisePropertyChanged(); 
            }
        }
        private void adddata1()
        {
            contextdb.Studentinformation.Add(_studentObj);
            contextdb.SaveChanges();
            MessageBox.Show("Insert Successfully.....");
            DataList = new ObservableCollection<StudentData>(contextdb.Studentinformation);


        }
    }
}

Here, is the code to add student data. In this ViewModel, we can add ObservableCollection for a list of student data, add their properties, and add MessageBox for showing the success message.


Step: 5

Now, we create a design for adding Student data.

<xmp>
<Window x:Class="WPFMVVMFramework.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFMVVMFramework"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="50"/>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock Text="FirstName" Grid.Column="0" Grid.Row="0"/>
        <TextBox Grid.Column="1" Grid.Row="0" Text="{Binding Path=StudentObj.StudentFirstOrLastName}"/>
        <TextBlock Text="LastName" Grid.Column="0" Grid.Row="1" />
        <TextBox Grid.Column="1" Grid.Row="1" Text="{Binding Path=StudentObj.StudentCast}"/>
        <Button Content="Add" Grid.Column="0" Grid.Row="2" Height="30" Width="50" Command="{Binding Userlist}">

        </Button>
        <DataGrid AutoGenerateColumns="False" x:Name="datagrid1" ItemsSource="{Binding DataList}" Grid.Column="0" Grid.Row="3" Background="LightGray" RowBackground="LightYellow" AlternatingRowBackground="LightBlue" BorderThickness="5">
            <DataGrid.Columns>
                <DataGridTextColumn Header="FirstName" Binding="{Binding StudentFirstOrLastName}"/>
                <DataGridTextColumn Header="LastName" Binding="{Binding StudentCast}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

</xmp>

Here, we can bind the View with the ViewModel. In this view, we can use the grid for adding data and DataGrid for showing data.


Output:

Image: Fill the data

Image: Success Message

Image: Data Added Successfully

Conclusion

The prior advantage of using MVVM Framework is to provide a clear separation between business logic and presentation. Using MVVM Framework we can accelerate speed and performance enhancements.

  • Pin It
TOP