Click here to Skip to main content
15,885,782 members
Articles / Desktop Programming / WPF
Tip/Trick

WPF and MVVM pattern

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
5 Aug 2014CPOL2 min read 13.5K   8  
Introduction to WPF technology and the MVVM design pattern

Introduction

In this article I want to talk about WPF  technology with the MVVM pattern, this theme will spans more than one item, I will start with the principles of MVVM  and in the next article we will move to other things

What is MVVM ? 

MVVM is a pattern that helps to separate the presentation layer UI  of the Buissiness layer ,so in the WPF project the developer focuses on its code and the designer also on its UI model.

To implement the pattern we need to create a View (xaml) and ViewModel (C#), first time I will show you how to display data from the ViewModel in our view.

Using the code

So,  in VS2012  we create a new WPF Project, Visual Studio automatically adds a default view named MainWindow, We will use this view for our example :

Image 1

C#
<Window x:Class="WPF_MVVM.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>
        <TextBlock Text="{binding ViewModelProperty}" Margin="208,124,245,159"/>
    </Grid>

</Window>




// the code behind of the view

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;

namespace WPF_MVVM
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

In this view we have created a textblock that will display the property of our ViewModel,

With the binding we will find our property in the context of the view which I will explain in the article.

Text="{binding ViewModelProperty}"

Image 2

Now we will create our ViewModel that will contain our ViewModelProperty, our ViewModel implements the INotifyPropertyChanged interface that contains an event to notify UI  when ViewModelProperty changes value.

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

namespace WPF_MVVM.ViewModel
{
    public class ViewModel : INotifyPropertyChanged
    {
        private string _viewModelProperty;
        public string ViewModelProperty
        {
            get { return _viewModelProperty; }
            set
            {
                _viewModelProperty = value;
                OnPropertyChanged("ViewModelProperty");
            }
        }

        public ViewModel(string message)
        {
            ViewModelProperty = message;

        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
#if DEBUG
            if (this.GetType().GetProperty(propertyName) == null)
                throw new Exception("Property does not exist");
#endif
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }

        }
    }

}

 

In the Code-behind of view we have to change the DataContext , the DataContext is a property of the view inherited by all visual elements  (TextBlock , Buttons, Grid...etc), it allows to combine our presentation layer (MainWindow)  with the business layer (ViewModel).

public MainWindow()
        {
            string messageToDisplay="This is my first article in CodeProject"; 
            InitializeComponent();
            this.DataContext=new ViewModel(messageToDisplay);
        }

Press F5 ,it is magic :

Image 3

Now , we can imagine that our ViewModel can also retrieve informations from a database or other sources.

Conclusuion 

This is my first article on CodeProject, it's just a small introduction to the MVVM pattern, I am trying to prepare for another articles around this technology than'll be published soon, In my next article I will talk about a complex use of viewmodel in the context of a real project archtecture.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
France France
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --