All posts by Jeremy

Very simple MVVM demo application

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 🙂

Using extension methods to raise an event

While reviewing some code at work the last days, I noticed I had a lot of similar methods I used to raise events. Basically, I did a test to check if the EventHandler is not null, and in this case, I raise the event:

// declaration of the event
public event EventHandler Saved;

// method I use to raise the event
private void OnSaved()
{
  if (this.Saved != null)
    this.Saved(this, EventArgs.Empty);
}

In some of my classes, I had around 10 methods like this one to do the check, and raise the event if the associated event handler is not null. I was thinking about creating an extension method that would do this job for me… And actually, it’s very simple ! Here is the code:

 /// 
/// Raise an event with a given EventArgs
/// 
/// EventHandler to raised
/// Sender of the event
/// Argument of the event
public static void Raise(this EventHandler handler, object sender, EventArgs e)
{
    if (handler != null)
    {
        handler(sender, e);
    }
}

Now, I can remove all methods that looks like the first I mentioned in the post, and simply write

Saved.Raise(this, EventArgs.Empty);

I also created an overload of the extension method that does not supply an EventArgs (in case you want to use EventArgs.Empty) and also a generic version (in case you want to use an EventHandler).
You can download the associated class here.