WPF改进了自动滚动到DataGrid VirtualingStackPanel中新添加的项目

时间:2015-10-07 10:02:47

标签: wpf performance datagrid virtualization autoscroll

我有这个代码在DataGrid中使用VirtualingStackPanel实现“自动滚动到新添加的项目”行为(模式=回收):

    protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue)
    {
        base.OnItemsSourceChanged(oldValue, newValue);

        if (oldValue is INotifyCollectionChanged)
            (oldValue as INotifyCollectionChanged).CollectionChanged -= ItemsCollectionChanged;

        if (!(newValue is INotifyCollectionChanged)) return;

        (newValue as INotifyCollectionChanged).CollectionChanged += ItemsCollectionChanged;
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        // Dig out and store a reference to our internal ScrollViewer  
        _scrollViewer = RecursiveVisualChildFinder<ScrollViewer>(this) as ScrollViewer;
        _vsp = GetInnerStackPanel(this);
        if (_scrollViewer != null )
        {
            //UpdateLayout();
            _scrollViewer.ScrollToBottom();
        }
    }

    private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (_scrollViewer != null && e.Action == NotifyCollectionChangedAction.Add)
        {
            //UpdateLayout();
            //_needRefresh = true;
            _stopWatch.Start();
            _scrollViewer.ScrollToBottom();
            _stopWatch.Stop();
            _measures.Add(_stopWatch.ElapsedMilliseconds);
        }
    }

此解决方案的问题在于性能:调用“_scrollViewer.ScrollToBottom()”与项目计数的时间呈线性关系:例如:在我的测试中,我有1000个项目的1 ms因子,所以如果我有超过1 000 000项,自动滚动需要超过1秒!

如何获取datagrid(或任何带有VirtualingStackPanel的ItemControl)以快速滚动到最后一个项目?

感谢您的想法:)

0 个答案:

没有答案