Featured Post

Organize and rename photos by EXIF data with PowerShell

This PowerShell script organizes and renames all photos in a selected folder using EXIF data. It will also create thumbnails of the images i...

Tuesday, October 8, 2013

C# WPF/Silverlight MVVM Beginners Tutorial 101 Part I

Welcome to a multi-part tutorial to help walk you through how to get started developing a WPF or Silverlight application utilizing the MVVM design pattern.

MVVM = Model, View, ViewModel

Our ViewModels primary role is to control the data displayed on our View, data pulled from our Model. The Microsoft Prism library supplies (among other things we can use later) the NotificationObject class which we will use to Notify our View when Properties Change.

Each of our ViewModels will inherit from our BaseViewModel class that we will create first.

Prerequisites

Using VisualStudio, start a New Project > Visual C# > Silverlight > Silverlight Application

Note: We use Silverlight for Web applications and WPF for Desktop applications. Most Silverlight controls are supported in WPF while there are some WPF controls that are not available in Silverlight, so it would be recommended to design your application using Silverlight to be compatible on both platforms. See Contrasting Silverlight and WPF for more information.

Using NuGet, install Prism to supply our NotifyPropertyChanged utilities:

Visual Studio > Tools > Library Package Manager > Package Manager Console

PM> Install-Package Prism

Now the Prism dll files have been added to your Project References folder and we can refer to the Prism Namespace in our code.

On to the code

Create a new Class: BaseViewModel.cs

At the top, include the Prism references, and the class inherits from Prism's NotificationObject:

BaseViewModel.cs:

using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.ViewModel;

namespace MyApp
{
    public class BaseViewModel : NotificationObject
    {
    }
}

Lets create a new Class: CarrotViewModel.cs

namespace MyApp
{
    public class CarrotViewModel : BaseViewModel
    {
    }
}

Because our CarrotViewModel inherits from our BaseViewModel, which inherits from Prism NotificationObject, any Property in our CarrotViewModel can now support RaisePropertyChanged method.

In Part II we will add some Properties and have them update our UI, after all that is the whole point of an application usually!

to be continued in Part II...

No comments:

Post a Comment