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.
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?
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.
.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With