How can I have a ListBox auto-scroll when a new item is added?

后端 未结 12 2389
走了就别回头了
走了就别回头了 2020-11-28 20:34

I have a WPF ListBox that is set to scroll horizontally. The ItemsSource is bound to an ObservableCollection in my ViewModel class. Every time a new item is added, I want th

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 20:49

    solution for Datagrid (the same for ListBox, only substitute DataGrid with ListBox class)

        private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                int count = AssociatedObject.Items.Count;
                if (count == 0)
                    return;
    
                var item = AssociatedObject.Items[count - 1];
    
                if (AssociatedObject is DataGrid)
                {
                    DataGrid grid = (AssociatedObject as DataGrid);
                    grid.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        grid.UpdateLayout();
                        grid.ScrollIntoView(item, null);
                    }));
                }
    
            }
        }
    

提交回复
热议问题