【发布时间】:2017-12-05 13:45:50
【问题描述】:
提前致谢。
据我所知,您的应用启动时创建的第一个视图称为主视图,而其他视图(包括您通过在应用代码中调用 CreateNewView 创建的所有视图)是辅助视图。
我也知道,如果它们是 不是 UI 线程,我无法在线程中更新 UI。
我在网上搜索了很长时间,但没有找到任何东西。请帮助并尝试给出一些想法如何实现这一点。
这是我的代码,为简单起见已简化:
如果我在页面启动时加载项目:
public sealed partial class MainPage : Page
{
private ObservableCollection<Item> Items;//a GridView bind in this.
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
Items= new ObservableCollection<Item>();
Update();
}
async void Update()
{
//such as I have a lot of Items
foreach(Item i in Itemlist)
{
Items.add(i);
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
CoreApplicationView newView = CoreApplication.CreateNewView();
int newViewId = 0;
await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
Frame frame = new Frame();
frame.Navigate(typeof(MainPage), null);
Window.Current.Content = frame;
// You have to activate the window in order to show it later.
Window.Current.Activate();
newViewId = ApplicationView.GetForCurrentView().Id;
});
bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
}
}
问题来了:
众所周知,
ObservableCollection<T>有NotifyCollectionChangedEventHandler,当数据发生变化时,它会通知 UI 线程。但是辅助视图(一个新的 MainPage),当它运行时,UpDate() 方法改变了 Items 列表,然后出错(一个 GridView Bind in this)。
应用程序调用了为不同线程编组的接口。 (来自 HRESULT 的异常:0x8001010E (RPC_E_WRONG_THREAD))” 在 Windows.UI.Xaml.Controls.Image.put_Source(ImageSource 值) 在 APP1.MainPage.XamlBindingSetters.Set_Windows_UI_Xaml_Controls_Image_Source(图像 obj,ImageSource 值,字符串 targetNullValue) 在 APP1.MainPage.MainPage_obj2_Bindings.Update_image(BitmapImage obj, Int32 阶段) 在 APP1.MainPage.MainPage_obj2_Bindings.Update_(FloderItem obj, Int32 阶段) 在 APP1.MainPage.MainPa
我的意见是数据发生了变化,并且 ObservableCollection 调用了一个事件来更新辅助视图的 UI,但不在 UI 线程中。
我认为如果在 UI 线程中使用 NotifyCollectionChangedEvent 就可以了。
有人有想法吗?非常感谢。
【问题讨论】:
-
从代码中某处的错误看来,您正试图从空值加载
Image。这就是它抛出异常的原因,空值在您的数据源中。 -
非常感谢 Ahmar,我想我找到了问题,因为你,我调用了一个静态对象 :)
标签: c# multithreading uwp