How to close a View from a ViewModel ?

.Net, Events, WPF 15 Comments »

Note: I wrote this article to clarify relationships between ViewModel and View classes. If you want a complete solution you should take a look at existing MVVM framework like Cinch (by Sacha Barber).

Yesterday, there was an insteresting question about MVVM on StackOverflow: “How to close a View from a ViewModel ?”

Like always with WPF, there are many approaches to solve this problem.

Solution 1: give a reference to the View in the ViewModel

You need to control the View from the ViewModel ? Just gives a reference to the View in the ViewModel constructor.

?View Code CSHARP
1
2
3
4
public Window1()
{
  this.DataContext = new Window1ViewModel(this);
}

Unfortunatelly, this approach has several drawbacks:

  • it breaks the foundamental principle of the MVVM methodology: the ViewModel should be an abstraction of the View
  • it complicates the work needed to unit test your ViewModel
  • it introduces high coupling between the ViewModel and the View

Solution 2: the ViewModel raises an event when it wants to close its associated View

If having a reference to the View in the ViewModel is not the right thing, why not using an event. We can add a RequestClose event in the ViewModel class and raise this event when the ViewModel wants to close its associated View.

The View, when it creates the ViewModel subscribe to the RequestClose event. In the event handler, the View is closed.

?View Code CSHARP
1
2
3
4
5
6
7
8
// class is omitted, only constructor is shown
public Window1()
{
  var viewmodel = new Window1ViewModel();
  viewmodel.RequestClose += (s, e) => this.Close();
 
  this.DataContext = viewmodel;
}

Solution 2, first refinement

Of course I prefer the event based solution, but we can improve it. The first refinement we can do is to make sure the event will be coherent over all our classes. To achieve this I setup an interface:

?View Code CSHARP
1
2
3
4
public interface IRequestCloseViewModel
{
  event EventHandler RequestClose
}

This interface is implemented by my ViewModel classes which wants to support the ability to close their associated Views.

Solution 3, second refinement

Another possible refinement is to automate the subscription of the RequestClose event in the View. To do that, I created an abstract ApplicationWindowBase class that inherits from Window. When the DataContext changes, I check if the IRequestCloseViewModel is supported by the DataContext:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class ApplicationWindowBase : Window
{
  public ApplicationWindowBase()
  {
    this.DataContextChanged += new DependencyPropertyChangedEventHandler(this.OnDataContextChanged);
  }
 
  private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
  {
    if (e.NewValue is IRequestCloseViewModel)
    {
      // if the new datacontext supports the IRequestCloseViewModel we can use
      // the event to be notified when the associated viewmodel wants to close
      // the window
      ((IRequestCloseViewModel)e.NewValue).RequestClose += (s, e) => this.Close();
    }
  }
}

Like I said in the intro, this a very basic implementation of this concept. Many other approach exists. A good source of information is in the source code of existing MVVM frameworks.

French article about MVVM posted !

WPF 1 Comment »

It’s finally online after a long work.I hope my french readers will enjoy it:  http://japf.developpez.com/tutoriels/dotnet/mvvm-pour-des-applications-wpf-bien-architecturees-et-testables/

Here is the abstract translated to english:

“Inch by inch, the WPF technology is being adopted by .Net developers as a development platform for next generation user interfaces. This changeover is taking time and complicated because WPF changes principles that are well known until now in the process of designing a user interface. The Model-View-ViewModel methodology helps formalize WPF developement by giving guidance that leads to apps cleary architectured, testable, and by optimizing the workflow between developer and designer.”

Very simple MVVM demo application

WPF 25 Comments »

The last couple of days, I’ve been busy writing an article about MVVM in French. I don’t know yet if I’ll translate it to English, but I’m sure I can share the demo application, and this is the goal of this post !

I think the best way to understand how things fit together is to explore the source code of the application.

It’s a very small demo because I wanted to demonstrate only a subset of MVVM facilities, so you’ll find:

  • an easy way to work with commands in MVVM using Josh Smith RelayCommand class
  • the power of the ICollectionView interface to implement navigation and search feature
  • empty code-behind file for my views
  • a base class for all my ViewModel objects (again, based on the work of Josh)

mvvm-demo-1

mvvm-demo-2

You can download the source code here. Enjoy :-)

Why should I use Model-View-ViewModel pattern

WPF 2 Comments »

Recently, while discussing a WPF issue on a forum, I discovered that some people didn’t know anything about the Model-View-ViewModel pattern. I’m not an expert of MVVM as I discovered it a couple of months ago. I started to use it on my first real project at work, which involve a pretty big application using advanced TreeView, Ribbon, on-demand graphic creation, a C++ kernel, datagrid, etc. The MVVM pattern helps me to keep my design as clean as possible. In this post, I’d like to give you some of the aspects of the MVVM pattern, and useful links across the web.

If you find yourself:

  • having huge .xaml.cs code behind file
  • using event handler (such as Click…) everywhere
  • tweaking TreeViewItem (using ItemContainerGenerator for example) to manipulate a TreeView
  • having tons of IValueConverter
  • … then MVVM might come to the rescue :p

What MVVM can offer?

  • a clean and well defined separation between the Model and the View
  • the possibility to easily leverage the power of WPF: databinding, commands, validation, and more
  • a code that is testable
  • an organization that facilitate the workflow between designers and developers
  • minimalist code-behind file (which leads to testable code)
  • facilitate the deployment of an application in multiple environment (WPF / Silverlight)

How is that possible?

Here is a part of the introduction of John Gossman:

“In simple examples, the View is data bound directly to the Model. For example, a boolean in the Model can be data bound to a CheckBox, or a string field to a TextBox. In practice however, only a small subset of application UI can be data bound directly to the Model, especially if the Model is a pre-existing class or data schema over which the application developer has no control.
The Model is very likely to have a data types that cannot be mapped directly to controls.  Finally we need a place to put view state such as selection or modes.
The ViewModel is responsible for these tasks.  In this latter role the ViewModel contains data-transformers that convert Model types into View types, and it contains Commands the View can use to interact with the Model.”

viewmodel

  • The View has the associated ViewModel set as its DataContext so that the View can easily data bind to ViewModel properties
  • The ViewModel reflects its changes to the Model by calling appropriate methods on the Model
  • The ViewModel exposes ICommand that the View data bind to, in order to execute actions
  • The Model signals its changes to the ViewModel by raising events

What are good resources to start working with MVVM?

  • Karl Shifflett started a series about MVVM, you can find his work here.
  • Karl and Josh Smith wrote a very nice application that uses MVVM pattern. Moreover the application contains also information about internalization support. Check out the CodeProject article here.
  • Karl wrote an article about a very important concept: user input validation. This is the first article of his new MVVM series.
  • WPF architect, John Gossman wrote a series of blog post about MVVM on his blog. An introduction to MVVM is available and a good point to start.
  • Josh Smith wrote an excellent tool, Crack.Net which is built using MVVM. Crack.Net is hosted on CodePlex, and studying the source code is a very good manner to understand how stuff fits together in the MVVM world.
  • Josh Smith wrote an article about applying MVVM concepts to the WPF treeview. If you must work with a complex treeview, then you MUST read this article.
  • Marlon Grech wrote an article about ICollectionView. ICollectionView is a useful interface that can be used in ViewModel classes to keep track user selection

If you never heard about MVVM, or never take the time to look at it, I suggest you to take a look at some of those links. Trust me, the investisment worth it !

Learn Model-View-ViewModel, LOB WPF/Silverlight application

WPF No Comments »

I’ve been waiting for a long time for this, and Karl Shifflet finally did it !

Karl is a WPF guru, and he just started a new series of articles on Model-View-ViewModel. Here is his own introduction: “My goal is to provide an introduction, several simple examples and progress to a series of WPF LOB scenarios where M-V-VM is used.  Scenarios like, dialog box, simple form, master – detail, complex master detail with several embedded ViewModels, etc.”

I’m sure this series will very soon become the reference to learn MVVM. His first article is about validating the user input in a concise and agile way. Right now, I can’t give more details because I just start to read the article, but I’ll try to give my feedback as soon as possible.

Thinking in WPF: attached properties

WPF 1 Comment »

Today, I decided to start a series that I’m calling “Thinking in WPF”. As you already know, I do NOT consider myself as a WPF specialist, so those blog posts don’t aim at giving a perfect knowledge of the “best” (if there are any) ways of thinking in WPF. I’d just like to share what I’m experiencing :-)

In my previous post, I started to write about things that I think makes WPF different. In the current project I’m working on at work, I had a good example of a new way of thinking with WPF. Todays article deals with a new WPF concept called Attached properties.

Read the rest of this entry »

Read on a forum: only problems with WPF…

WPF 2 Comments »

A couple of days ago, I found a post on a WPF forum with the title “Only problems with WPF…”, and it basically looks like the following:

“When I installed VS.net express 2008, I was happy because I thought that with WPF I’ll be able to build nice UI. Unfortunately, I have the felling this is more like a source of problems… I spent several hours to fill a ListView with some data and the result is dirtier than with WinForms. The designer in VS.net sucks and  many controls are missing. It was so simple before…”

I wanted to give my point of view about that kind of reasoning because a couple of months ago, I think I had more or less the same… So, what makes WPF so different ? Or why I cannot just use my WinForms background and start to build wonderfull apps ?

I think that WPF is more than just a new framework or new classes. It is more than that because when you work with WPF, you have to change the way you think and design your apps.

  • You have to change the way your work with controls because you can apply new Style and Template to them so that you can completely change the way they look
  • You have to change the way you design your apps because of DataBinding and Commands
  • You have to… forget almost every things you already know, and be ready to learn again !

If I can give an advice, I would suggest to read a good WPF book. A couple of weeks ago, I finished to read WPF unleashed, by Adam Nathan 1, and I really think that having this kind of the book is the right way start working with WPF. A lot of cool website are also full of interesting resources, CodeProject is maybe the one that I like the most.

To conlude, I would like to give a quick example 2.

Imagine you’d like to build an application to browse a catalog of products. For each product, you need to see the name of the product, its designer, a description and an image. You also would like to have navigation build around the use of 2 arrows to browse products:

Building a WPF application

How could you achieve this ? You might think about several ways to do it. The point is that you can do this by only using a ListBox and changing its style ! Isn’t amazing ? Go ahead and check the full video at http://sessions.visitmix.com/.

  1. available at amazon.com
  2. I was inspired by CT06: Applications = Designers + Developpers at Mix08 available here
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in