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.
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.
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.
For asynchronous binding and refreshing of the DataGrid, consider using INotifyPropertyChanged on your ViewModel properties and invoking the Dispatcher to refresh the UI elements.
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