【发布时间】:2019-09-01 21:19:01
【问题描述】:
我的问题是针对 UWP,但 WPF 中的解决方案可能相同,所以我也标记了它。
我正在尝试在自定义gridview和listView中实现@ Extension方法,以便在选择更改时,所选项目始终将始终为视图进行动画。
扩展方法效果很好。但是获取 UIElement 容器来发送它并没有那么好。
ListView.Items 绑定到 ViewModel 中的集合。所以 ListView.Items 不是 UIElements,而是数据对象。我需要 SelectedItem 对应的 UIElement 容器。
首先我尝试了这个:
void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_scrollViewer != null && this.ItemsPanelRoot != null && this.Items.Count > 0)
{
var selectedListViewItem = this.ItemsPanelRoot.Children[this.SelectedIndex];
if (selectedListViewItem != null)
{
_scrollViewer.ScrollToElement(selectedListViewItem);
}
}
}
这起初有效,但实际上并不好。随着布局的动态更新,“ListView.ItemsPanelRoot.Children”的索引最终开始偏离“ListView.Items”。
然后我尝试了这个,到目前为止似乎工作正常:
void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_scrollViewer != null && this.Items.Count > 0)
{
var selectedListViewItem = this.ItemsPanelRoot.FindDescendants<ListViewItem>()
.Where(x => x.Content == this.SelectedItem).FirstOrDefault();
if (selectedListViewItem != null)
{
_scrollViewer.ScrollToElement(selectedListViewItem);
}
else
{
throw new Exception();
}
}
}
问题在于,每次执行该查询似乎都非常昂贵,而且也不安全,因为无法保证容器可用。我觉得(希望)我遗漏了一些东西,并且有一种正确的方法可以做到这一点。
注意:“FindDescendants”是 Windows UI Toolkit 的扩展方法,与 VisualTreeHelper 的作用相同。
【问题讨论】:
-
你可以看看ListView的ItemContainerGenerator。在 UWP 中,ItemsControl 中还有一个ContainerFromItem 方法。
-
大声笑,这正是我想要的。不知道我是如何在文档中错过的,我想我期待的是一个属性而不是一个方法。谢谢一百万,请随时回答。