简体   繁体   中英

Alternatives for static events WPF MVVM

I was trying to connect two viewmodels with each other and ended up using static events . Here is overview of what I got.

  1. MainViewModel

  2. 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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM