This project has moved and is read-only. For the latest updates, please go here.

ViewModel ---> View-Code-Behind

Feb 6, 2010 at 11:17 AM
Edited Feb 6, 2010 at 4:17 PM


while I am really happy with the architecture imposed by MVVMlight on my application so far there is one pattern I felt I had to use which made me feel a bit uncomfortable.

It concerns the interaction from ViewModel to code-behind:
In some scenarios changing the bound VM-property (base for the View's itemsource) does not reflect in the view - this is for example the case for a GraphSharp control or a DataGrid. Another scenario when this pattern occurs in my app is when I want to set the focus on a (rich-)textbox.
So I needed to call the respective Refresh() / Recalculate() / Focus() method on the control. Coming from the ViewModel I have no direct access to the control-object (as thats obviously the concern of the View - my ViewModel should not be aware of the WPF control, should it?)

So far I solved this problem by exposing for example a RequestRefresh-Event in the ViewModel the View (in its code behind) subscribes to in its DataContextChanged event-handler.
This works, but felt quite dirty somehow. How do you guys solve this?

Thanks a bunch and yet again cheers for this great and lightweight framework,

p.s. really sorry if this question shows just a major ignorance of the MVVM pattern ;-(


Feb 7, 2010 at 6:28 PM


This is probably the most discussed pattern around MVVM, so no ignorance there at all, you're just in the same boat as us all :) In fact, there is an interesting discussion around this right now on the WPF Disciples group:

(check the latest messages in the thread). Glenn Block speaks of 6 different manners to communicate with the View.

 1. INPC / Property binding

2. Events

3. Messages (Event Aggregator/Messenger/RX framework)

4. Through an intermediary such as a service

5. Through an interface

6. Through delegates (View passes delegates to the VM which it can use to call it back. For example VM might expose a SetActions method which the View calls passing it delegates.

Which method you choose depends very much on your scenario and personal preferences. For myself, I rely on bindings (of course), on Messages and sometimes on one or the other of the six.



Feb 7, 2010 at 7:25 PM

Hi Laurent,
thank you a lot for your reply. I didnt consider messages yet - thats interesting - especially as I felt I had underused that feature of your framework so far.

Again thank you and have a nice week,
Hinnerk :-)