c# - 类中的 Dispatcher.invoke 问题:C#
问题描述
这是我的代码的一部分:
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:提到的代码在我创建的类的内部无效!
解决方案
在您的问题中,您在this.Dispatcher.Invoke((Action)delegate
自定义类中使用。this
指的是该类内部的函数。您的自定义类没有Dispatcher
.
而是使用:App.Current.Dispatcher.Invoke((Action)delegate
并确保包含此代码的自定义类位于您的App
命名空间下。
推荐阅读
- sql - 如何在SQL中拆分顺序格式不一致的字符串
- clang - 在 Travis-ci 上编译 LLVM
- python - Django 静态文件无法加载到谷歌计算引擎上
- android - Lint 在组装发布目标时发现了致命错误
- reactjs - 有没有办法将 CRA 与 PHP 后端一起使用?
- ruby - nokogiri 的语法错误,意外的“。” 在 nokogiri::CSS 对象之后
- azure - Azure 网站无法与第三方 API 通信
- python - 如何将 mako 中的模板拆分为多个文件/目录?
- spring - 如何使用spring和hibernate从数据库中检索数据并在jsp中打印?
- python - ML 引擎从作曲家失败 - 未知名称“python-version”