Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-31 20:06:01
Original
869 people have browsed it

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

<code class="csharp">public void Load()
{
    matchList = new List<GetMatchDetailsDC>();
    matchList = proxy.GetMatch().ToList();

    foreach (EfesBet.DataContract.GetMatchDetailsDC match in matchList)
    {
        App.Current.Dispatcher.Invoke((Action)delegate
        {
            _matchObsCollection.Add(match);
        });
    }
}</code>
Copy after login

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.

The above is the detailed content of How to Modify an ObservableCollection From a Non-Dispatcher Thread in WPF?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!