Scroll WPF Listview to specific line

前端 未结 11 1025
孤城傲影
孤城傲影 2020-11-30 02:34

WPF, Browserlike app.
I got one page containing a ListView. After calling a PageFunction I add a line to the ListView, and want to scroll the new line into view:

11条回答
  •  日久生厌
    2020-11-30 03:04

    Try this

    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                ScrollViewer scrollViewer = GetScrollViewer(lstVw) as ScrollViewer;
                scrollViewer.ScrollToHorizontalOffset(dataRowToFocus.RowIndex);
                if (dataRowToFocus.RowIndex < 2)
                    lstVw.ScrollIntoView((Entity)lstVw.Items[0]);
                else
                    lstVw.ScrollIntoView(e.AddedItems[0]);
            } 
    
     public static DependencyObject GetScrollViewer(DependencyObject o)
            {
                if (o is ScrollViewer)
                { return o; }
    
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(o); i++)
                {
                    var child = VisualTreeHelper.GetChild(o, i);
    
                    var result = GetScrollViewer(child);
                    if (result == null)
                    {
                        continue;
                    }
                    else
                    {
                        return result;
                    }
                }
                return null;
            } 
    
    private void Focus()
    {
     lstVw.SelectedIndex = dataRowToFocus.RowIndex;
     lstVw.SelectedItem = (Entity)dataRowToFocus.Row;
    
     ListViewItem lvi = (ListViewItem)lstVw.ItemContainerGenerator.ContainerFromItem(lstVw.SelectedItem);
    ContentPresenter contentPresenter = FindVisualChild(lvi);
    contentPresenter.Focus();
    contentPresenter.BringIntoView();
    
    }
    

提交回复
热议问题