What is the best way to automatically scroll the list to the last item added?

I use ListViewto show a list of errors that occur in my application. It behaves and looks exactly like the error list in Visual Studio. I want to add automatic scrolling when the last error item is selected (for example, like automatically scrolling a Visual Studio log window when placing a caret at the end).

The error list is in ObservableCollection, which is passed in ListView.ItemsSourceas follows:

public ObservableCollection<ErrorListItem> Items;
... 
MyListView.ItemsSource = _Items;

I tried to do an automatic scroll in the event handler _Items_CollectionChanged, but since this event is on ItemsSource, not on the actual ListViewItems, it is a pain to find out if the last item is selected, select a new line, etc. This is especially difficult, as it seems that ListViewItemsthey are not created instantly. I was able to auto-scroll, delaying the call, to set the last item selected as follows:

void _Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    // determine the last item to select from 'e'
    ...        

    _ItemPendingToBeScrolled = newItemToSelect;
    ListView.SelectedItem = newItemToSelect;


    Dispatcher.BeginInvoke(DispatcherPriority.Background, 
        (ThreadStart)delegate 
        { 
            if (_ItemPendingToBeScrolled != null)
            {
                ListView.ScrollIntoView(_ItemPendingToBeScrolled);
                ItemPendingToBeScrolled = null;
            } 
        })
}

But this is obviously not the right way to do this. In addition, I want everything to continue to work if the list is filtered (without checking the last item in my source and the last one ListViewItemin ListView).

, ListViewItem ListView ? , . , ?

+3
1

listboxes/listviews , , CollectionChanged? ObservableCollection , List, .

, , , , , EventArgs

0

Source: https://habr.com/ru/post/1707225/


All Articles