I believe explicitly using the data context in the code behind of the view (custom, user control etc) in any MVVM application is an anti-pattern. The view has no need to explicitly access the data context it is there purely for binding concerns. The following screen shot illustrates what I mean:
This is an anti-pattern because the view knows about the view model - as you can see the data context is being cast to the DataContextViewModel. The view (user control) is explicitly coupled to the view model and has reduced the cohesiveness of the view - it can now only be bound to instance of DataContextViewModel. Now you could argue if it was interface this would make is more useful but this doesn't reduce the tight coupling it just gives the illusion.
I guess the reason why this is common is because it makes the XAML appear very clean and simple, but this is also not ideal because it's not obvious what's being bound between the view model and the view:
How should this have been done?
By defining a Dependancy Property on the view (user control) and then binding this in the XAML to the FirstNames property of the view model, then there is no need to access the DataContext in the code behind of the view:
The XAML has now changed to be more declarative, which is a good thing:)
This is an anti-pattern because the view knows about the view model - as you can see the data context is being cast to the DataContextViewModel. The view (user control) is explicitly coupled to the view model and has reduced the cohesiveness of the view - it can now only be bound to instance of DataContextViewModel. Now you could argue if it was interface this would make is more useful but this doesn't reduce the tight coupling it just gives the illusion.
I guess the reason why this is common is because it makes the XAML appear very clean and simple, but this is also not ideal because it's not obvious what's being bound between the view model and the view:
How should this have been done?
By defining a Dependancy Property on the view (user control) and then binding this in the XAML to the FirstNames property of the view model, then there is no need to access the DataContext in the code behind of the view:
The XAML has now changed to be more declarative, which is a good thing:)
Can you imagine doing this for each control inside an View...the ViewModel is a part of presentation layer and should be treated as such.
ReplyDelete