提问者:小点点

.NET Framework,WPF:取消函数引发事件


我有一个函数来处理一个事件

public void Delete(bool raiseEvent)
{
       if (raiseEvent)
       {
           RaiseEvent(new EdgeDeletedRoutedEventArgs(DeletedEvent, this));
       }
       ....some other stuff
}

我订阅该功能如下:

Class.Delete += SomethingDeleted;

void SomethingDeleted(object sender, EdgeDeletedRoutedEventArgs e)
{
    if (someCondition)
    {
        // here i want to cancel the delete function which raises the event
    }  
}

怎么可能取消删除功能,这样“其他东西”就不会在不中断我的应用程序的情况下执行呢?

我尝试在SomethingDeleted中抛出一个异常,并在Delete中捕获该异常,但它中断了我的应用程序和id,以保持应用程序运行。


共1个答案

匿名用户

bool cancel属性添加到EdgeDeletedRoutedEventArgs(与CancelEventArgs一样)

public void Delete(bool raiseEvent)
{
       if (raiseEvent)
       {
           var args = new EdgeDeletedRoutedEventArgs(DeletedEvent, this);
           RaiseEvent(args);
           if (args.Cancel) return;
       }
       ....some other stuff
}

void SomethingDeleted(object sender, EdgeDeletedRoutedEventArgs e)
{
    if (someCondition)
    {
         e.Cancel = true;
         return;
    }  
}

如果您不真正需要RoutedEvent功能,请使用常规事件(event EventHandlerDelete;)并从CancelEventArgs继承EdgeDeletedEventArgs