-1

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

subminer
  • 37
  • 1
  • 8

1 Answers1

0

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
StepUp
  • 36,391
  • 15
  • 88
  • 148
  • @subminer feel free to ask any question. If you feel that my reply helps to you, then you can mark my reply as an answer to simplify future search of other people. Please, read this http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – StepUp Apr 05 '16 at 08:40