【发布时间】:2019-02-19 10:46:33
【问题描述】:
这是我的代码的一部分:
public void refreshShowCase()
{
for (int i = 0; i < 12; ++i)
{
bitmapImage[i] = new BitmapImage(new Uri(posterURLCollection[i]));
image[i] = new Image { Source = bitmapImage[i] }; //Error occurs here****
}
}
当我运行这个时,我得到这个错误:调用线程必须是 STA,因为许多 UI 组件都需要这个。
所以我在Disapther.Invoke 中添加我的代码
this.Dispatcher.Invoke((Action)delegate
{
BitmapImage[] bitmapImage = new BitmapImage[14];
Image[] image = new Image[14];
//Do a loop for defining Bitmaps sources
for (int i = 0; i < 12; ++i)
{
bitmapImage[i] = new BitmapImage(new Uri(posterURLCollection[i]));
image[i] = new Image { Source = bitmapImage[i] };
}
}
现在我有这个错误:'Dispatcher' 在当前上下文中不存在!
我应该如何解决这个问题?请帮忙。
Update1:提到的代码在我创建的类的内部!
【问题讨论】:
-
System.Windows.Application.Current.Dispatcher.Invoke 工作吗?
-
@Adam:当我使用它时,我得到这个:“应用程序”类型中不存在“当前”
-
您收到编译时错误或运行时错误?
-
@SoumenMukherjee:当我不使用 Dispatcher 时,我会收到我提到的运行时错误:调用线程必须是 STA,因为许多 UI 组件都需要这个。但是,当我使用 Dispatcher 时,
This.Dispatcher下方会出现一条红线,上面写着:“Dispatcher”在当前上下文中不存在! -
我的水晶球说你写了一个 UWP 应用,而不是 WPF 应用。 stackoverflow.com/questions/16477190/…
标签: c# .net windows visual-studio