"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Modify an ObservableCollection From a Non-Dispatcher Thread in WPF?

How to Modify an ObservableCollection From a Non-Dispatcher Thread in WPF?

Published on 2024-11-08
Browse:526

How to Modify an ObservableCollection From a Non-Dispatcher Thread in WPF?

"This Type of CollectionView Does Not Support Changes to Its SourceCollection from a Thread Different from the Dispatcher Thread"

Problem Description

A DataGrid bound to an asynchronously populated ObservableCollection throws an error stating that changes to the SourceCollection are not permitted from a non-Dispatcher thread.

Solution

The problem arises from thread affinity. The ObservableCollection is initially created on the UI thread, making it accessible only from the UI thread. To modify it from a different thread, the delegate must be placed on the UI Dispatcher.

Updated ViewModel Code

public void Load()
{
    matchList = new List();
    matchList = proxy.GetMatch().ToList();

    foreach (EfesBet.DataContract.GetMatchDetailsDC match in matchList)
    {
        App.Current.Dispatcher.Invoke((Action)delegate
        {
            _matchObsCollection.Add(match);
        });
    }
}

By invoking the delegate on the UI Dispatcher, the additions to the ObservableCollection are scheduled on the UI thread, resolving the exception.

Enhanced Binding and Refresh

For asynchronous binding and refreshing of the DataGrid, consider using INotifyPropertyChanged on your ViewModel properties and invoking the Dispatcher to refresh the UI elements.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3