开发者

WPF DataGrid bound to an ObservableCollection that is updated on separate thread fails to maintain sort

开发者 https://www.devze.com 2023-02-13 22:05 出处:网络
Download Sample Project I have a wpf 4 datagrid that is bound to an ObservableCollection. This ObservableCollection is

Download Sample Project

I have a wpf 4 datagrid that is bound to an ObservableCollection. This ObservableCollection is updated on another thread. I can see the updates coming through to my simple gui just fine. I can even sort the data. But the sort does not "stick". It will sort once when you click the column header but when a value in the collection changes the sort does not change accordingly.

The MainWindow backing code is where most of the action goes down (jus开发者_开发问答t for simplicity of the example). I create an ObservableCollection and pass it to a thread that does the actual writes to the ObservableCollection. I then bind that same ObservableCollection to the datagrid via a CollectionView (I've tried binding it directly as well). My hunch is that the sorting depends upon the collectionChanged event which I'm pretty sure won't fire back to the Dispatcher ( see: http://bea.stollnitz.com/blog/?p=34).

What to do?

    public partial class MainWindow : Window
{
    private Thread _dataThread;
    private Thread _marketThread;
    private SampleData _sampleData;
    private Market _market;
    private ObservableCollection<Stock> stocks;
    private ConcurrentQueue<Stock> _updates = new ConcurrentQueue<Stock>();
    public MainWindow()
    {
        InitializeComponent();

        stocks = new ObservableCollection<Stock>();

        for (var i = 0; i < 5; i++)
        {
            var newStock = new Stock();
            newStock.Id = (uint)i;
            stocks.Add(newStock);
        }

        var source = CollectionViewSource.GetDefaultView(stocks);

        dataGrid.ItemsSource = source;
        _sampleData = new SampleData(_updates);
        _dataThread = new Thread(_sampleData.CreateData) { Name = "Data Thread" };
        _dataThread.Start();

        _market = new Market(_updates, stocks);
        _marketThread = new Thread(_market.Start){Name = "Market Thread"};
        _marketThread.Start();

    }

}

Challenge.

Download Sample Project


Have you looked at ObjectDataProvider IsAsynchonous="True" and bind in XAML? You might be able to not thread the collection creation. I have no experience how DataGrid sorts behave behind IsAsynchonous="True".

    <ObjectDataProvider IsAsynchonous="True" ...>
0

精彩评论

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