views:

205

answers:

2

What is a good pattern for sharing data between related views?.

I have an application where 1 form contains many small views, each views behaves independently from each other more or less (they communicate/interact via an event bus). Every so often I need to pass the same objects to the child views. Sometimes I need this same object to be passed to a child view and then the child passes it onto another child itself contains.

What is a good approach to sharing this data between all the views contained within the parent form (view) ?

I have looked into CAB and their approach and every "view" has a "root work item" this work item has dictionary that contains a shared "state" between the views that are contained.

Is this the best approach? just a shared dictionary all the views under a root view can access?

My current approach right now is to have a function on the view that allows one to set the object for that view. Something like

view.SetCustomer(Customer c); 

then if the view contains a child view it knows to set it on the child view ala:

this.childview1.SetCustomer(c);

The application is written in C# 3.5, for winforms using MVP with structure map as a IoC/DI provider.

A: 

Josh Smith and Marlon Grech use the mediator pattern with an implementation that uses weak references to prevent memory leaks. Check this out:

http://marlongrech.wordpress.com/2009/04/16/mediator-v2-for-mvvm-wpf-and-silverlight-applications/

panamack
i'm now using a variation of the mediator pattern with the event system. basically firing events for when shared data is loaded so views that needed will get it and use it. Thank you.
Dovix
A: 

Seems like the shared data should belong in the underlying Model, not the View.

As far as how this sharing takes place, I'd assume that something is creating the individual Views, and giving them a reference to their Model? That seems like the appropriate mechanism for the sharing to use.

kyoryu
you are right, I started approching the UI data with more DTOs instead of just trying to use the model directly and this has help break the need for sharing an instance.
Dovix
The rise in popularity of DTOs seems to be solving a huge amount of problems. Funny, that - after years of OO orthodoxy, we're starting to realize that hey, there's some value to these 'struct' things after all! The more things change...
kyoryu
Yep. DTO is a good tool for just getting what you need to ship it straight into the UI without extra bloat. Too bad just like all the other patterns/methods people just abuse them till become an issue. Skillz go a long way :)
Dovix