检查是否已成功完成所有附加方法

时间:2012-01-07 14:01:35

标签: c# silverlight events xaml

我正在开发一个Silverlight LOB应用程序。 由于一些必需的功能,我为所有页面创建了一个新的NewBasePage类。此类派生自Page类。我添加了几个事件并手动提升它们。

但我坚持一些东西。我需要检查绑定到某个事件的所有方法是否都已成功完成。有没有办法做到这一点?

新基类:

public class NewPageBase : Page
{
        public void RefreshData(Action resultAction = null)
        {
            if (StartRefreshingData != null) StartRefreshingData(this, null);

            if (resultAction != null) resultAction();
        }

        public event EventHandler StartRefreshingData;

}

的Xaml:

<newbase:NewBasePage ...>

...

  <i:Interraction.Triggers>
    <i:EventTrigger EventName="StartRefreshingData">
        <i:InvokeCommandAction Command="{StaticResource someCommandFromViewModel}"/>
    </i:EventTrigger>
  </i:Interraction.Triggers>
</newbase:NewBasePage>

1 个答案:

答案 0 :(得分:1)

如果您想知道任何事件处理程序是否未能完成其工作,您可以抛出异常或提供自定义EventArgs类型,以跟踪任何事件处理程序是否失败。

public class FailureEventArgs : EventArgs // not the best name, I know
{
    private bool _failed;

    public bool Failed
    {
        get { return _failed; }
        set { _failed |= value; }
    }
}

用法:

// Event declaration
public event EventHandler<FailureEventArgs> MyFailingEvent;

// Event invocation
private void Invoke()
{
    bool failure = false;
    var handler = MyFailingEvent;
    if (handler != null)
    {
        var args = new FailureEventArgs();
        handler(this, args);
        failure = args.Failed;
    }

    // more code, aware of possible failure
}

// In your event handler
private void OnEvent(object sender, FailureEventArgs args)
{
    var errorOccured = false;

    // some code which could set errorOccured to true

    args.Failure = errorOccured;
}

而且,正如我在上面的评论中已经提到的,一旦事件的调用结束,你就可以确定没有附加的事件处理程序了。