EventHandler总是为空?

时间:2016-04-04 12:12:51

标签: c# wpf events event-handling uap

我想创建一个事件,订阅是在另一个ViewModel上。事件处理程序在第一个ViewModel上始终为null。 在第一个Viewmodel中,我声明了Event并引发如下

  public event EventHandler EditSearchChanged;

并提升为

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

在第二个Viewmodel中,我声明了第一个Viewmodel的属性。

   private EditTileViewModel editTileVM;

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

并按如下方式订阅活动

EditTileVM.EditSearchChanged += EditTileVM_EditSearchChanged;

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

调试器结果 enter image description here

1 个答案:

答案 0 :(得分:0)

当您在以下属性中创建ViewModel的另一个新实例时,会发生这种情况:

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

因此有EditViewModel的两个实例。

我建议您在Prism框架的两个viewModels之间使用EventAggregator pattern

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

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

请参阅关于simplified Event Aggregator pattern的Rachel Lim的非常好的教程。

或使用MVVM Light messenger

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

// Broadcast
Messenger.Default.Send<CloseAppliactionMessage