EventHandler is always null?

581 Views Asked by At

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 enter image description here

1

There are 1 best solutions below

0
On

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