开发者

WPF DataGrid not showing all rows

开发者 https://www.devze.com 2023-02-09 21:26 出处:网络
I have an ObservableCollec开发者_运维百科tion bound to a WPF DataGrid. The ObservableCollection is populated and updated asynchronously.

I have an ObservableCollec开发者_运维百科tion bound to a WPF DataGrid. The ObservableCollection is populated and updated asynchronously.

The DataGrid is not displaying the correct number of rows. Each time I run the application I get a varying number rows displayed, usually 7-8 but sometimes only one. I get the same behvaior with ListBox, but not with ComboBox.

I get this same behavior with a ListBox and ItemsControl but not with ComboBox. The ComboBox correctly displays all 18 items as expected.

EDIT

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

I'll need to do some more detective work here as my presumption was the updates were happening in the same thread. So the reason for the first few items being displayed correctly is that the ViewModel was able to retrieve some of the data before the View itself loaded.


I can confirm that this is indeed a threading issue. I am an idiot for dumping the exceptions when adding to the collection, because I probably would have spotted the error sooner! Never do this! It is bad pratice.

Possible solutions to this problem are addressed here:

ObservableCollection and threading


Use this code:
(Notice that DownloadedItem and it´s properties must also be using INotifyPropertyChanged as in this example)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace WpfApplication1
{
    class Downloads : NotifyBase
    {
        public virtual ObservableCollection<DownloadedItem> DownloadedItemCollection
        {
            get { return _DownloadedItemCollection; }
            set { _DownloadedItemCollection = value; OnPropertyChanged(System.Reflection.MethodBase.GetCurrentMethod().Name.Substring(4));  /*OnPropertyChanged("DownloadedItemCollection");*/ }
        } private ObservableCollection<DownloadedItem> _DownloadedItemCollection;

    }
}

public class NotifyBase : INotifyPropertyChanged
{
    #region NotifyBase
    // Declare the event
    public virtual event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号