WPF: how to signal an event from ViewModel to View without code in codebehind?

Tomáš Kafka picture Tomáš Kafka · Dec 12, 2009 · Viewed 34.4k times · Source

I have quite simple (I hope :)) problem:

In MVVM, View usually listens on changes of ViewModel's properties. However, I would sometimes like to listen on event, so that, for example, View could start animation, or close window, when VM signals.

Doing it via bool property with NotifyPropertyChanged (and starting animation only when it changes from false to true) is possible, but it feels like a hack, I'd much prefer to expose event, as it is semantically correct.

Also, I'd like to do it without code in codebehind, as doing viewModel.myEvent += handler there would mean that I'd have manually unregister the event in order to allow View to be GC'd - WPF Views are already able to listen on properties 'weakly', and I'd much prefer to program only declaratively in View.

The standard strong event subscription is also bad, because I need to switch multiple ViewModels for one View (because creating View every time takes too much CPU time).

Thank you for ideas (if there is a standard solution, a link to msdn will suffice)!

Answer

Kent Boogaart picture Kent Boogaart · Dec 12, 2009

Some comments:

  • You can use the weak event pattern to ensure that the view can be GC'd even if it is still attached to the view model's event
  • If you're already switching multiple VMs in for the one view, wouldn't that be the ideal place to attach/detach the handler?
  • Depending on your exact scenario, you could just have the VM expose a state property which the view uses as a trigger for animations, transitions, and other visual changes. Visual state manager is great for this kind of thing.