Home > Backend Development > C++ > body text

How to Resolve \'This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread\'?

Linda Hamilton
Release: 2024-10-31 09:39:01
Original
460 people have browsed it

How to Resolve

Error: "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread"

Problem:

The error occurs when modifying an ObservableCollection on a thread other than the UI thread.

Solution:

1. Using Dispatcher.Invoke:

To update the ObservableCollection from a different thread, invoke the changes on the UI thread using Dispatcher.Invoke.

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);
        });
    }
}
Copy after login

2. Using async/await:

Alternatively, you can use async/await to execute the Load method asynchronously on the UI thread.

public void LoadAsync()
{
    Task.Run(async () =>
    {
        matchList = new List<GetMatchDetailsDC>();
        matchList = await proxy.GetMatchAsync();

        await Dispatcher.InvokeAsync(() =>
        {
            foreach (EfesBet.DataContract.GetMatchDetailsDC match in matchList)
            {
                _matchObsCollection.Add(match);
            }
        });
    });
}
Copy after login

DataGrid Binding and Refreshing:

Binding:

<DataGrid ItemsSource="{Binding MatchObsCollection}"/>
Copy after login

Refreshing Asynchronously:

To refresh the DataGrid asynchronously, call the Refresh method on the dispatcher in a delegate.

public void RefreshDataGridAsync()
{
    Task.Run(() =>
    {
        Dispatcher.InvokeAsync(() =>
        {
            dataGridParent.ItemsSource = null;
            dataGridParent.ItemsSource = MatchObsCollection;
        });
    });
}
Copy after login

The above is the detailed content of How to Resolve \'This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread\'?. 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!