我只想在另一個線程中更改窗口的背景。有兩個程序,一個是工作正確的,另一個拋出InvalidOperationException。使用由其他線程創建的對象
權代碼:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Thread t = new Thread(new ParameterizedThreadStart(threadTest));
t.Start(@"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg");
}
void threadTest(object obj)
{
string path = obj as string;
this.Dispatcher.Invoke(new Func<object>(() => this.Background = new
}
}
的錯誤代碼:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Thread t = new Thread(new ParameterizedThreadStart(threadTest));
t.Start(@"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg");
}
void threadTest(object obj)
{
string path = obj as string;
//this.Dispatcher.Invoke(new Func<object>(() => this.Background = new ImageBrush(new BitmapImage(new Uri(path)))));
ImageBrush background = new ImageBrush(new BitmapImage(new Uri(path)));
this.Dispatcher.Invoke(new Func<object>(() => this.Background = background));
}
}
不同,這些代碼之間是,錯誤代碼創建的子線程的圖像刷對象。 所以我的問題是:在wpf程序中,線程是否只能使用由自己的線程創建的對象? 感謝您的任何答覆。
如果UI線程只能使用自己創建的對象,是否有任何方法讓其他線程通過對象到UI線程? – adream307 2012-04-21 06:17:51
@ adream307當然有,請參閱我的編輯:) – 2012-04-21 14:28:46