我有一个MainWindow,它包含DemoUI(一个UserControl)的实例。
在一个名为DemoModule的类实例中,我有一个对DemoUI的引用,我称之为_demoUI
。
当我试图使用从DemoModule中获得对主窗口的引用时
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;
}
从这里包含的代码来看,似乎不需要获取progressBar引用来更新_demoUI上的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);