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
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.