Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set viewmodel property from code-behind using Viewmodel-first?

In my WPF (4.0) application I'm using Viewmodel-first pattern. Hence, my viewmodels are created first, then the views - using data templates. A working demo can be found here.

Now, from within the created views (code-behind), I need to modify a property of the viewmodel. In a View-first approach, I would simply access a named viewmodel instance. However, the Viewmodel-first approach does not allow for this. There is a viewmodel, but the view does not care what it is.

BAD:

Sure you can get hold of the DataContext and use it, but that effectively couples the view and t the viewmodel.

private void MyView_Loaded(object sender, RoutedEventArgs e)
{
    this.viewModel = DataContext as MyViewModel;
}

There has to be a recommended pattern for this. Commands? Messages? Please help!

Q: How do I modify (set a property) the active viewmodel?

like image 257
l33t Avatar asked Jan 11 '13 10:01

l33t


2 Answers

Use Bindings to pass data from View to ViewModel and commands to active the ViewModel.

Commands should use a binding to a execute a Command on the ViewModel.

Messages should be used to communicate between ViewModels.

.

like image 82
Emond Avatar answered Sep 19 '22 13:09

Emond


You can't do that. Otherwise View will be aware about View Model.

If this initialization is common across all view models, then you can define the properties/events in ViewModelBase and derive all view models from this class.

Q: How do I modify (set a property) the active viewmodel?

You need to use EventAggregator pattern for View-ViewModel communication.

You can use your favorite MVVM framework, and nearly all framework support EventAggregator (or MessageBus or Enterprise Bus).

like image 45
Tilak Avatar answered Sep 20 '22 13:09

Tilak