C#: Error with PivotItem creation

-2

After PivotItem pivotItem = new PivotItem(); I'm getting Additional information: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)). What should it be? I'm pretty confused of it.

Code:

foreach (Source source in sources)
{
    PivotItem pivotItem = new PivotItem(); /* At this point it falls. */
    pivotItem.Header = source.Name;
    pivotItem.Margin = new Thickness(0, -10, 0, 0);

    ListView listView = new ListView();
    listView.ItemsSource = source.Articles;
    listView.ItemTemplate = (DataTemplate)Resources["MainItemTemplate"];
    listView.ItemClick += OpenArticle_ItemClick;
    listView.SelectionMode = ListViewSelectionMode.None;
    listView.IsItemClickEnabled = true;

    pivotItem.Content = listView;
    pvtMain.Items.Add(pivotItem);
}
c#
win-universal-app
asked on Stack Overflow Feb 27, 2016 by Jan Chalupa • edited Feb 27, 2016 by Jan Chalupa

1 Answer

1

Based on the exception, you seem to be trying to create a new PivotItem in a thread other than the UI thread. You are only allowed to interact with the UI elements in the UI thread.

You're probably calling this code from an event handler that wasn't triggered from a UI event. You should be able to resolve the issue by using the Dispatcher to switch back to the UI thread:

await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
    foreach (Source source in sources)
    {
        PivotItem pivotItem = new PivotItem(); /* At this point it falls. */
        pivotItem.Header = source.Name;
        pivotItem.Margin = new Thickness(0, -10, 0, 0);

        ListView listView = new ListView();
        listView.ItemsSource = source.Articles;
        listView.ItemTemplate = (DataTemplate)Resources["MainItemTemplate"];
        listView.ItemClick += OpenArticle_ItemClick;
        listView.SelectionMode = ListViewSelectionMode.None;
        listView.IsItemClickEnabled = true;

        pivotItem.Content = listView;
        pvtMain.Items.Add(pivotItem);
    }
});
answered on Stack Overflow Feb 27, 2016 by Damir Arh • edited Feb 28, 2016 by Damir Arh

User contributions licensed under CC BY-SA 3.0