Tuesday, June 15, 2010

MVVM, ViewModel-DataContext and WPF

 

There seems to be a view taken by people,strategies-of-binding, that data binding from the View to the ViewModel should be done in a standard way and NO OTHER WAY.

This seems silly to me, as there are some many different ways to do it, and many more contexts when you need to use a different approach.

I preferred using UserControls for my views. The binding method I commonly use is to use the XAML <UserControl.DataContext>, NOT THE CODE BEHIND FILE

i.e.

<UserControl x:Class=”SomeNamespace.View.AControl” xmlns:ViewModel="clr-namespace:ANamespace.ViewModel"... >

<UserControl.DataContext><vm:AControlViewModel/></UserControl.DataContext>

</UserControl>

But in some cases this is limited. For Example, I want a ViewModeled UserControl “UC_B” within another ViewModeled UserControl “UC_A” and have “UC_A”s ViewModel use “UC_B”s ViewModel Properties

i.e. A Reusable DICOM Connection Parameters UserControl

<UserControl>

<UserControl.DataContext><vm:UC_SearchStudyControlViewModel/></UserControl.DataContext> <View:DicomConnectionParametersControl x:Name="SearchConnectionParameters" DataContext="{Binding Path=UC_ConnectionParametersViewModel}" DockPanel.Dock="Top" /> ...

</UserControl>

So now I’m still binding via the DataContext of the View to the View’s ViewModel, but in a different way i.e. the ViewModel is a Property of another ViewModel. This could not be done with the previous example, the Views ViewModel is within a different Views ViewModel.

i.e. B.DataContext = A.DataContext.Bs_ViewModel

Note there are other ways to pass data between ViewModel,i.e. Messenger , and there are some drawbacks, Binding to Large CLR Objects, in this implementation if you have a large ViewModel. The Dependencies between the ViewModels is also increased by this, i.e. if Bs_ViewModel changes A might need refactoring, but the simplicity of this solution, compared implementing a Messenger, outweighs the minor dependency increase.

No comments:

Post a Comment