如何在 MVVM WPF 应用程序中控制 ListBox 的滚动位置 [英] How to control the scroll position of a ListBox in a MVVM WPF app
问题描述
我有一个启用了垂直滚动的大列表框,我的 MVVM 有新建和编辑 ICommands.我正在向集合的末尾添加新项目,但我希望滚动条也能在调用 MVVM-AddCommand 时自动定位到 End.我还在应用程序的其他部分使项目可编辑(通过使用特定行项目调用 EditCommand),以便我的 ListBoxItem 使用 DataTrigger 进入编辑模式,但是我将如何将该特定行(ListBoxItem)带到视图中通过调整滚动位置.
I have got a big ListBox with vertical scrolling enabled, my MVVM has New and Edit ICommands. I am adding new item to the end of the collection but I want the scrollbar also to auto position to the End when I call my MVVM-AddCommand. I am also making an item editable(By calling EditCommand with a particular row item) from some other part of the application so that my ListBoxItem getting in to edit mode using DataTrigger, but how will I bring that particular row(ListBoxItem) to the view by adjusting the scroll position.
如果我在视图端执行此操作,我可以调用 listBox.ScrollInToView(lstBoxItem).但是从 MVVM 的角度来看,解决这个常见的 Scroll 问题的最佳方法是什么.
If I am doing it in the View side I can call listBox.ScrollInToView(lstBoxItem). But what is the best way to solve this common Scroll issue from an MVVM perspective.
推荐答案
我通常在 ListBox
上设置 IsSynchronizedWithCurrentItem="True"
.然后我添加一个 SelectionChanged
处理程序并始终将所选项目带入视图,代码如下:
I typically set IsSynchronizedWithCurrentItem="True"
on the ListBox
. Then I add a SelectionChanged
handler and always bring the selected item into view, with code like this:
private void BringSelectionIntoView(object sender, SelectionChangedEventArgs e)
{
Selector selector = sender as Selector;
if (selector is ListBox)
{
(selector as ListBox).ScrollIntoView(selector.SelectedItem);
}
}
我可以从我的 VM 获取默认集合视图并使用 MoveCurrent*()
方法之一来确保正在编辑的项目是当前项目.
From my VM I can get the default collection view and use one of the MoveCurrent*()
methods to ensure that the item being edited is the current item.
CollectionViewSource.GetDefaultView(_myCollection).MoveCurrentTo(thisItem);
注意:编辑为使用 ListBox.ScrollIntoView()
来适应虚拟化
NOTE: Edited to use ListBox.ScrollIntoView()
to accomodate virtualization
这篇关于如何在 MVVM WPF 应用程序中控制 ListBox 的滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!