Rashim's Blog

Archive for the ‘WPF’ Category

Some days ago when I was working in PRISM I needed to send some notifications from one view to another based on some business logic. This is something like that, if a view receives any notification from other resources, the view requires changing its appearance. To handle this type of situation we usually remove the view, update its properties and add the view in the particular region again. Another way we do it by using the .NET framework’s Events mechanism but this is not loosely coupled.

In PRISM there is a nice way to do that specially to communicate in different view/Module (User controls, Entities, External project resources and so forth) by using EventAggregator service.

The EventAggregator service is primarily a container for events that allow decoupling of originators and receivers so that they can develop autonomously.

I share with you some of my code portion in which I have used EventAggregator service,

This is the entity class,

public class Company
    public Company()
    { }

    public int CompanyID { get; set; }
    public string CompanyName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Postcode { get; set; }
    public Country Country { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime? DateModified { get; set; }

The event that i have used has been given below. The publisher and subscriber will use this event to communicate with themselves,

public class CompanyAddedEvent : CompositePresentationEvent<Company>

MyEventAggregator class which is basically for the EventAggregator instance,

public class MyEventAggregator
    private static EventAggregator myEventAggregator = null;

    private static readonly object syncLock = new object();

    private MyEventAggregator() { }

    public static EventAggregator GetEventAggregator()
        lock (syncLock)
            if (myEventAggregator == null)
                myEventAggregator = new EventAggregator();

            return myEventAggregator;

Event Publishing,

MyEventAggregator.GetEventAggregator().GetEvent<CompanyAddedEvent>().Publish(your company Object);

Event Subscription,

MyEventAggregator.GetEventAggregator().GetEvent<CompanyAddedEvent>().Subscribe((company) =>
            ////DO Whatever you want
        }, false);

One thing here i need to add, the publisher and subscriber do not have a direct reference to each other.That is multiple publishers can raise the same event and multiple subscribers can listen to the same event.

In this way, the event may subscribe by the different view/module and, once the event is published, the subscriber will get the notification and can start its task according that. This is a very easy stuff but by using this facility you could do very nice and cool things..However,If you want to know in details please have a look on that [^]

Blog Stats

  • 189,209 hits


%d bloggers like this: