如何在XAML中将ScrollIntoView用于ListView [英] How to use ScrollIntoView for ListView in xaml
问题描述
我有一个ControlTemplate在ListView中显示项目. ListView有500多个项目.我正在保存状态,并从XML中获取选定的项目,然后将其发送到listview以默认选择它,以供下次导航到屏幕时使用.
I have a ControlTemplate to show Items in ListView. ListView is having 500+ items. I am preserving the state and getting selected item from XML and sending it to listview to select it by default for next navigation to the screen.
我的问题是我如何通过xaml设置选定的项目(可能出现在最后一个,即看不见的项目). ViewModel不知道任何UI控件,因此我无法在ViewModel中应用ScrollIntoView方法.
My problem is How can I set selected item (which may be present in last i.e. out of view) by xaml. ViewModel doesn't know about any UI control, so I cant apply ScrollIntoView method in ViewModel.
我可以使用任何二传手"或样式"来做到这一点吗?
Can I use any Setter or Style to do this?
请提出建议.
推荐答案
我最近使用DataGrid做到了这一点.诀窍是将自定义行为附加到视图.这样.
I've recently done this with a DataGrid. The trick is to attach a custom Behavior to your View. Like that.
<ListView ... >
<iy:Interaction.Behaviors>
<ext:ScrollIntoViewBehavior />
</iy:Interaction.Behaviors>
...
</ListView>
和相关的班级:
public class ScrollIntoViewBehavior : Behavior<ListView>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.SelectionChanged += new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.SelectionChanged -= new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
}
private void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sender is ListView)
{
ListView grid = (sender as ListView);
if (grid.SelectedItem != null)
{
grid.Dispatcher.BeginInvoke(() =>
{
grid.UpdateLayout();
grid.ScrollIntoView(grid.SelectedItem);
});
}
}
}
}
一些需要注意的事情:
- 添加对System.Windows.Interactivity程序集的引用
- 在视图中添加相应的名称空间:xmlns:iy = http://schemas.microsoft. com/expression/2010/interactivity
这篇关于如何在XAML中将ScrollIntoView用于ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!