Scroll WPF Listview to specific line

前端 未结 11 1033
孤城傲影
孤城傲影 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:08

    To overcome the virtualisation issue but still use ScrollIntoView and not hacking around in the guts of the ListView, you could also use your ViewModel objects to determine what is selected. Assuming that you have ViewModel objects in your list that feature an IsSelected property. You'd link the items to the ListView in XAML like this:

    
      
        
      
    
    

    Then, the code-behind method can scroll to the first selected item with this:

    var firstSelected = PersonsListView.Items
        .OfType().FirstOrDefault(x => x.IsSelected);
    if (firstSelected != null)
        CoObjectsListView.ScrollIntoView(firstSelected);
    

    This also works if the selected item is well out of view. In my experiment, the PersonsListView.SelectedItem property was null, but of course your ViewModel IsSelected property is always there. Be sure to call this method after all binding and loading has completed (with the right DispatcherPriority).

    Using the ViewCommand pattern, your ViewModel code could look like this:

    PersonVMs.ForEach(vm => vm.IsSelected = false);
    PersonVMs.Add(newPersonVM);
    newPersonVM.IsSelected = true;
    ViewCommandManager.InvokeLoaded("ScrollToSelectedPerson");
    

提交回复
热议问题