【问题标题】:What's a Good Way to Obtain ListView Item Containers?获取 ListView 项容器的好方法是什么?
【发布时间】: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 中还有一个Container​From​Item 方法。
  • 大声笑,这正是我想要的。不知道我是如何在文档中错过的,我想我期待的是一个属性而不是一个方法。谢谢一百万,请随时回答。

标签: wpf uwp


【解决方案1】:

ItemsControls 有一个 Item​Container​Generator 属性,它包含一个 Item​Container​Generator 对象,您可以使用它来获取项目和项目索引等的项目容器。

例如

var container = listView.ItemContainerGenerator.ContainerFromItem(item);

在UWP中,ContainerFromItem等类似方法也可以直接在ItemsControl类中使用,方便你编写

var container = listView.ContainerFromItem(item);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多