I was trying to connect two viewmodels
with each other and ended up using static events
. Here is overview of what I got.
MainViewModel
ChildViewModel
I was trying to instantiate the ChildViewModel in the MainViewModel Constructor
ChildViewModel childViewModel;
public MainWindowViewModel()
{
childViewModel = new ChildViewModel();
childViewModel.TextStatusChanged += ChildViewModel_TextStatusChanged;
}
But, this approach failed because the ChildViewModel
instance which was created here is ended up with the scope ending, also the ChildViewModel
instance which was created in it's related view is completely different than the one I created in the MainViewModel
.
I then changed this to use Static Events like this
public MainWindowViewModel()
{
ChildWindowViewModel.TextStatusChanged += ChildViewModel_TextStatusChanged;
}
It worked like charm but after after a little read I See that all people telling that static events are bad because they might lead to memory leak.
What alternatives to static events may I use, or how can I attach the same viewmodel
instance to hold the same event.
Maybe you should use an event aggregator.
https://www.codeproject.com/Articles/812461/Event-Aggregator-Pattern
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.