ViewModel binding approach

2 views
Skip to first unread message

Corrado Cavalli

unread,
Jul 30, 2008, 5:52:51 AM7/30/08
to wpf-di...@googlegroups.com

Another V-M-VM question for you (easier than my previous one…)

 

Let’s suppose to have a Window divided in 3 areas each one independent from each other, how do you provide ViewModels to those Areas?

 

Option 1: A common container esposing 3 properties ContextA,ContextB etc… associated to Windows’s DataContext and each area container bound using {Binding Container.ContextA}

Option 2: Each different ViewModel is explicitly bound to area’s datacontext, e.g:

 

Grid1.DataContext=new ContextA();

Grid2.DataContext=new ContextB();

Etc…

 

Option 3: Others?

 

I know that final result is the same, just curious about your way of working and pros/cons of each solution.

 

Corrado

Josh Smith

unread,
Jul 30, 2008, 6:00:28 AM7/30/08
to wpf-di...@googlegroups.com
I'd say, of course, it depends.  If you have complete control over the shape of your viewmodel, then there might be benefit in using your first approach. It could make the system more understandable and more accurately express the purpose and relationships of the VM classes. However, if you are working on a large team, building various components on different schedules, and need to composite them together (a la prism, perhaps) then it might not be possible to create one overarching viewmodel that contains the rest.  In that situation, your second approach makes sense.

Josh

JohnGossman

unread,
Jul 30, 2008, 10:44:25 AM7/30/08
to WPF Disciples
I'm very pragmatic, so my first instinct is to say "Whatever works",
but I prefer option 2) above. It reduces coupling and will make it
easier to pick up one of your sub-views and move it somewhere else.

Option 3)

Why not use DataTemplates? So your ViewModel would have a "Window"
and SubAreas that would be ViewModels and I would create DataTemplates
for each SubArea. The data binding system automatically expands the
DataTemplate when it sees a SubArea object and inside the DataTemplate
the DataContext is automatically set correctly. One advantage of this
is you can rearrange or add SubAreas and the same mechanism "just
works".

Corrado Cavalli

unread,
Jul 30, 2008, 2:41:14 PM7/30/08
to wpf-di...@googlegroups.com
Thanks Josh and John for your invaluable opinion, about DataTemplates: good
suggestion, I'll apply it asap! :-)

Corrado
Reply all
Reply to author
Forward
0 new messages