WPF BackgroundWorker完成从子用户控件到MainWindow的更新

时间:2011-02-08 09:49:30

标签: wpf

我在MainWindow中有动态加载UserControl。此UserControl通过调用BackgroundWorker来执行任务。完成后,我必须通知MainWindow。当worker完成时,它会进入内部用户控件中的workercompleted函数,但是如何让外部用户控件知道这个呢?

在我的情况下,我在工作人员启动时禁用按钮。我必须在工人完成时启用它,但不知道如何

2 个答案:

答案 0 :(得分:0)

您可以宣传该活动。因此,当BackgroundWorker完成后,您将引发另一个处于UserControl级别的事件,然后您可以在主窗口中观察它。

e.g。

partial class MyUserControl
{
    private readonly BackgroundWorker bgWorker = new BackgroundWorker();

    public event EventHandler BackgroundWorkerCompleted;

    private void InitializeComponent()
    {
        ...

        bgWorker.RunWorkerCompleted += delegate { OnBackgroundWorkerCompleted(); };
    }

    private void OnBackgroundWorkerCompleted()
    {
        if (BackgroundWorkerCompleted != null)
        {
            BackgroundWorkerCompleted(this, null);
        }
    }
}

然后你可以使用:

MyUserControl.BackgroundWorkerCompleted += delegate { EnableButton(); };
在你的窗口中

答案 1 :(得分:0)

您可以使用Routed Events。然后你上升一个路由事件,它将冒出可视树,并可以在父UI元素(如窗口)中处理。

在您的用户控件中定义路由事件,如下所示:

public static readonly RoutedEvent OperationCompletedEvent = EventManager.RegisterRoutedEvent(
    "OperationCompleted", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl));

public event RoutedEventHandler OperationCompleted
{
   add { AddHandler(OperationCompletedEvent, value); } 
   remove { RemoveHandler(OperationCompletedEvent, value); }
}

当后台工作程序操作完成时,使用用户控件上的RaiseEvent方法引发该事件:

protected virtual OnOperationCompleted() {
    RaiseEvent(new RoutedEventArgs(OperationCompletedEvent));
}

然后,在您的窗口中订阅此事件:

AddHandler(MyUserControl.OperationCompletedEvent, OnUserControlOperationCompleted);