Wp8 - 从应用程序重定向并返回时,EventHandler 为空

Wp8 - EventHandler is null when redirected from app and back

在我的应用程序中,我将简单的 EventHandler(在我的 ViewModel 中)定义为:

public event EventHandler FavouriteChangedEvent;

然后当我需要的时候,我用这个触发事件

FavouriteChangedEvent(this, null);

一切都按预期工作,但在我的应用程序中,有可点击的链接,可以打开网络浏览器(作为单独的应用程序)。当您返回应用程序时,然后当我尝试 运行 FavouriteChangedEvent(this, null); 它以 NullPointerException 结束(从调试来看是因为 FavouriteChangedEvent 确实为空)。

这是为什么?

我在网上找到并使用了它

    public delegate void EventHandler(object sender, string myValue);
    public event EventHandler FavouriteChangedEvent = delegate { }; 

但这并没有多大帮助。应用程序没有下降,但在我的视图 class 中,我在构造函数中有这一行 _dataContext.FavouriteChangedEvent += _dataContext_FavouriteChangedEvent;

出门回到app后,该事件不再触发

Then when I need, I fire the event with this

FavouriteChangedEvent(this, null);

it ends with NullPointerException (From debugging it is beacause FavouriteChangedEvent is really null

这是因为还没有事件处理程序

event是一个class

Once a class has declared an event, it can treat that event just like a field of the indicated delegate type. The field will either be null, if no client has hooked up a delegate to the event, or else it refers to a delegate that should be called when the event is invoked. Thus, invoking an event is generally done by first checking for null and then calling the event.

你至少要在上升事件前检查 null:

if(FavouriteChangedEvent != null)
    FavouriteChangedEvent(this, null);

注意,要使此线程安全,您必须将事件复制到局部变量,以确保同一事件发生 null 检查和上升:

var event = FavouriteChangedEvent;
if(event != null)
    event(this, null);

描述的解决方案(在构造时附加空委托)是另一种可能的线程安全解决方案。

根据event design guidelines

DO use a protected virtual method to raise each event

这就是说 - 不要像这样引发事件处理程序,而是调用将引发事件的受保护的虚拟方法(称为 OnFavouriteChangedEvent)。并且无需在事件名称中包含“事件”一词。简单点:FavouriteChanged.