开发者

WPF BackgroundWorker Completed Update from sub-usercontrol to MainWindow

I have a dynamically loading UserControl inside my MainWindow开发者_Python百科. This UserControl performs a task by calling BackgroundWorker. When this completes, I have to notify the MainWindow. When the worker completes, it enters the workercompleted function in the inner usercontrol but how can I let the outer user control know about this?

In my case, I'm disabling a button when the worker starts. I have to enable it when the worker completes but dont know how


You could propagate the event. So when the BackgroundWorker is completed you raise another event that is at the UserControl level, then you can observe that in the main window.

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);
        }
    }
}

then you can use:

MyUserControl.BackgroundWorkerCompleted += delegate { EnableButton(); };

in your window.


You can use Routed Events for that. Then you rise a routed event it will bubble up the visual tree and can be handled in parent UI elements (like your window).

In your user control define a routed event like this:

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); }
}

When the background worker operation completes raise that event using RaiseEvent method on the user control:

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

Then, subscribe to this event in your window:

AddHandler(MyUserControl.OperationCompletedEvent, OnUserControlOperationCompleted);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜