简体   繁体   中英

EventHandler is always null?

I want to create a event and subscribe is on another ViewModel. The event handler is always getting null on the first ViewModel. In the first Viewmodel I declared Event and raised as follows

  public event EventHandler EditSearchChanged;

and raised as

     if (EditSearchChanged != null)
        {
            EditSearchChanged(this, null);
        }

In the second Viewmodel,I have declared a property of first Viewmodel.

   private EditTileViewModel editTileVM;

    public EditTileViewModel EditTileVM
    {
        get
        {
            return editTileVM ?? (editTileVM = new EditTileViewModel());
        }
        set
        {
            editTileVM = value;
            RaisePropertyChanged();
        }
    }

and subscribe the event as follows

EditTileVM.EditSearchChanged += EditTileVM_EditSearchChanged;

  private void EditTileVM_EditSearchChanged(object sender, EventArgs e)
    {
        this.EditTileVM = (sender as EditTileViewModel);
    }

Debugger Result在此处输入图片说明

It happens as you create another new instance of ViewModel in the following property:

private EditTileViewModel editTileVM;
public EditTileViewModel EditTileVM
{
    get
    {
        return editTileVM ?? (editTileVM = new EditTileViewModel());
    }
    set
    {
        editTileVM = value;
        RaisePropertyChanged();
    }
}

So there are two instances of EditViewModel .

I suggest you to use EventAggregator pattern between two viewModels from Prism framework:

// Subscribe
eventAggregator.GetEvent<CloseAppliactionMessage>().Subscribe(ExitMethod);

// Broadcast
eventAggregator.GetEvent<CloseAppliactionMessage>().Publish();

Please, see a very good tutorial of Rachel Lim about simplified Event Aggregator pattern .

Or use MVVM Light messenger :

//Subscribe
Messenger.Default.Register<CloseAppliactionMessage>(ExitMethod);

// Broadcast
Messenger.Default.Send<CloseAppliactionMessage

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