Pages

Saturday, July 27, 2013

Communication Between Views in MVVM (Pub-Sub Pattern)


When you write WPF application you obviously use MVVM pattern. At some point you probably will need some communication between separated views. Well, there is a bunch of tools for this purposes -MVVM Light’s Messenger or Microsoft Prism’s EventAggregator, but today I'll show an alternative way by using Publish-Subscribe Pattern aka Observer.

Pub-Sub is a simple static class that will make your life easier with MVVM:
public delegate void PubSubEventHandler<T>(object sender, PubSubEventArgs<T> args);

public class PubSubEventArgs<T> : EventArgs
{
    public T Item { get; set; }

    public PubSubEventArgs(T item)
    {
        Item = item;
    }
}

public static class PubSub<T>
{
    private static Dictionary<string, PubSubEventHandler<T>> events = 
            new Dictionary<string, PubSubEventHandler<T>>();

    public static void AddEvent(string name, PubSubEventHandler<T> handler)
    {
        if (!events.ContainsKey(name))
            events.Add(name, handler);
    }
    public static void RaiseEvent(string name, object sender, PubSubEventArgs<T> args)
    {
        if (events.ContainsKey(name) && events[name] != null)
            events[name](sender, args);
    }
    public static void RegisterEvent(string name, PubSubEventHandler<T> handler)
    {
        if (events.ContainsKey(name))
            events[name] += handler;
    }
}