WPF InvalidOperationException获取MainWindow参考

时间:2014-04-10 18:50:51

标签: wpf wpf-controls

我有MainWindow,它包含一个DemoUI实例(一个UserControl)。

在名为DemoModule的类实例中,我引用了DemoUI,我称之为_demoUI

当我尝试使用

从DemoModule中获取对MainWindow的引用时

var parentWindow = Window.GetWindow(_demoUI);

我得到了InvalidOperationException

The calling thread cannot access this object because a different thread owns it.

最终,我希望能够使用它的Dispatcher更新MainWindow的进度条的值,如下所示:

var progressBar = parentWindow.FindName("ProgressBar") as ProgressBar;

progressBar.Dispatcher.Invoke(DispatcherPriority.Normal,
    new DispatcherOperationCallback(o => { 
        progressBar.Value = Progress = args.Current; 
        return null;
    }), null);

更新1

public void OnProgressChanged(object sender, ProgressChangedEventArgs args)
{
    Progress = Convert.ToInt32(args.Current * 100);
    var progressBar = Application.Current.MainWindow.FindName("ProgressBar") as ProgressBar;
    if (progressBar != null)
        progressBar.Value = Progress;
}

1 个答案:

答案 0 :(得分:0)

从您在此处包含的代码中,您似乎无需获取progressBar参考以更新_demoUI上的ProgressBar? MainWindow上还有另一个ProgressBar吗?无论如何,您可以使用_demoUI引用来访问调度程序。

_demoUI.Dispatcher.Invoke(DispatcherPriority.Normal,
    new DispatcherOperationCallback(o => { 
        _demoUI.ProgressBar.Value = Progress = args.Current; 
        return null;
    }), null);

或者

_demoUI.Dispatcher.BeginInvoke(DispatcherPriority.Background,
    new DispatcherOperationCallback(o => { 
        var window = Window.GetWindow(_demoUI);
        //do what you need to with the window here.


    }), null);