locked
Notify property changed from background task

    Question

  • I have this Items binds to a ListView.

    private ObservableCollection<MyItem> Items = new ObservableCollection<MyItem>();

    class MyItem : INotifyPropertyChanged { private string myProperty = null; public string MyProperty { get { return myProperty; } set { myProperty = value; OnPropertyChanged("MyProperty"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } }

    Now if I create create a background task and register a BackgroundTaskCompletedEventHandler like this

    backgroundTaskRegistration.Completed += registration_Completed;

    How can I let the completion event trigger some code to update the values within Items? (and subsequently cause the UI to update from the PropertyChanged event) 

    The code below obviously won't work because it is not running on UI thread. Wrap around the codes with Dispatcher.RunAsync will then throw NullPointException.

    void registration_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
    {
            int i = 15;
            foreach (MyItem item in Items)
            {
                 item.MyProperty = "New Item " + i++;
            }
    }

    If this is not the correct approach, how should I change it so that the UI will refresh upon background task completion?

    • Edited by chinlj Sunday, July 20, 2014 10:50 AM
    Sunday, July 20, 2014 10:46 AM

Answers

  • try this one:

    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync()
    


    Microsoft Certified Solutions Developer - Windows Store Apps Using C#

    • Marked as answer by chinlj Sunday, July 20, 2014 2:06 PM
    Sunday, July 20, 2014 12:00 PM

All replies

  • how do you get the Dispatcher?

    Microsoft Certified Solutions Developer - Windows Store Apps Using C#

    Sunday, July 20, 2014 11:29 AM
  • I'm only aware of this

    Window.Current.Dispatcher.RunAsync

    Sunday, July 20, 2014 11:43 AM
  • try this one:

    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync()
    


    Microsoft Certified Solutions Developer - Windows Store Apps Using C#

    • Marked as answer by chinlj Sunday, July 20, 2014 2:06 PM
    Sunday, July 20, 2014 12:00 PM