views:

50

answers:

4

Hello:

I'm currently developing a application where I will have multiple windows open using C# and WPF.

Is there a pattern or common methodology used to help faciliate communication between open Windows or/and UserControls?

For example, a window, let's call it the 'Hierarchy Window', may displays a hierarchy of countries, provinces, and cities in the world. Outside of that there are several other Windows which may display a province or city for example OR allow you to create a province or city. In the case of creating a new city, which is the best way for my 'City Window' to communicate with my 'Hierarachy Window' regarding adding a city or removing a city?

Keeping in mind that the 'Hierarchy Window' might not even be open when a City is created. At which point, there is no need for a response/action.

+1  A: 

There are two common approaches to this:

  1. Use Dependency Injection to inject a common service.
  2. Use a messenger of some form.

The second option is becoming very popular with WPF and Silverlight. Many common toolkits, such as MVVM Light (for details, see the Messenger class description), use this approach.

Reed Copsey
I checked out the MVVM Light and while although it isn't the direction I am going to go, comments on the website lead me to the PRISM framework and event aggregator. Thanks for the tip! A messenger pattern will do very well in my application.
Matthew
A: 

Just adding to what Reed wrote above:

When I have implemented this (in my case using MVVM) I have tended to go for a Messenger/Mediator pattern first to get things up and running and then refactor it to use Dependency Injection.

For a good example of the Mediator pattern have a look at Sasha Barbers MVVM framework called Cinch (on V2 now I think). You can download all the souce code and have a look at how he used the Mediator - its a very very good example. You can also have a look at the Microsoft Dev Lab project on Reactive Extensions for .NET which implement IObservable's and IObserver - not directly related to your question but a very cool way to do messaging.

For Dependency Injection have a look at the Microsoft Unity Application Block stuff

Hope that helps a bit.

jameschinnock
A: 

You could check out the PRISM framework (in WinForms this used to be CAB - Composite Application Block). It's a part of the Microsoft Patterns & Practices.
You can use event publication and subscription to communicate between objects in a very easy and straightforward way:

//publish:
 eventAggregator.GetEvent<ItemAddedEvent>().Publish(MyItem);

//subscribe:
eventAggregator.GetEvent<ItemAddedEvent>().Subscribe(MyMethod);

I haven't used it thoroughly enough yet, but they provide a whole lot of documentation and a whole sleek of features to support DI, Commands and Validation. Worth to check out!

Roel
A: 

To me, this sounds like you need to implement the Model-View-Presenter Pattern. See MVP on MSDN.

Marcel