WOW - there are like a thousand answers, and here I am going to add another one.
The really obvious thing in the why-not-I-implement-this-forehead-slap method is that the code-behind and the ViewModel are sitting in the same room to talk, so there is no reason why they are not allowed talk.
If you think about it, XAML is already closely connected with the ViewModel API, so you can just go and depend on it behind the code.
Other obvious rules for submission or ignoring still apply (interfaces, null checks <- especially if you use Blend ...)
I always make a property in code like this:
private ViewModelClass ViewModel { get { return DataContext as ViewModelClass; } }
This is the client code. Zero check is intended for hosting management, as in blend.
void someEventHandler(object sender, KeyDownEventArgs e) { if (ViewModel == null) return; ViewModel.HandleKeyDown(e); }
Manage your event in the code you want (the user interface events are user-oriented, so that's fine), and then use the ViewModelClass method, which can respond to this event. The problems are still divided.
ViewModelClass { public void HandleKeyDown(KeyEventArgs e) { } }
All these other attached properties and voodoo are very cool, and the methods are really useful for some other things, but here you can get away with something simpler ...
Pieter Breed Sep 18 '09 at 11:36 2009-09-18 11:36
source share