views:

66

answers:

1
+1  Q: 

MVVM and events

To keep code out of the view when using the Model-View-View Model pattern (aka Presentation Model), I can expose commands as properties in the view model and bind to those commands from the view. This way my views can be entirely written XAML and no code-behind, other than the mandatory constructor call to InitializeComponent().

This works well for controls that implement ICommandSource . But what if I want to run some action when the text of a textbox changes? The compiler refuses XAML where I set attach an handler that is not on the code-behind file to an event.

I can write some event handlers that simply run commands (or methods) in the view model, like this:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    ((EditPersonViewModel) DataContext).ChangeBioCommand.Execute(e.Changes);
}

This works, but I don't like the fact I have to write such ugly boilerplate code all over my views. Is there a better solution?

+2  A: 

You can use the "attached command behavior" pattern. Marlon Grech has a good implementation here.

Thomas Levesque
Exactly what I was looking for, thanks.
Martinho Fernandes