代码之家  ›  专栏  ›  技术社区  ›  Marks

WPF ListView-选择“视图字段”之外的项

  •  1
  • Marks  · 技术社区  · 16 年前

    我正在使用ListView在列表中显示项目。用户可以自己选择项目,或者使用一些“预选键”选择具有指定属性的项目。

    要检查我使用的项目,请执行以下操作:

    for(int i;i<MyListView.Items.Count;++i)
    {
        if( /*... Check if the items should be selected ...*/ )
            (MyListView.ItemContainerGenerator.ContainerFromIndex(i) as ListViewItem).IsSelected = true;
    }
    

    这对于执行时可见的项目非常有效。但对于不可见的项,containerFromIndex()返回空值。我听说这与虚拟化有关,而且这个列表不知道“视野”上下的项目。但是,当您手动选择项目时,如何能够将列表中的选定项目置于“视图字段”之外?

    如何选择“视野”之外的项目?我认为这是可能的。

    谢谢你的帮助, 标志

    2 回复  |  直到 16 年前
        1
  •  2
  •   Community Mohan Dere    9 年前

    正如您提到的,我猜问题在于ListView项的虚拟化。默认情况下,ListView(和ListBox)使用 VirtualizingStackPanel 作为他们的项目来提高绩效。可以阅读它如何工作的简要说明 here .

    但是,您可以替换另一个面板。在这种情况下,尝试使用普通的StackPanel。如果在ListView中有大量的项,特别是如果它们是复杂项,那么性能可能会受到影响。

    <ListView>
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel/>
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
    </ListView>
    

    编辑

    您也可以尝试解决所描述的问题 at this similar question ,取决于您的型号。但是,这可能对您不起作用。

        2
  •  0
  •   Peter Duniho    10 年前

    在处理虚拟化项控件时,禁用虚拟化的一个替代方法(实际上有时这是一个有用的功能,即使它会干扰API其他部分的正确操作)是找到 VirtualizingPanel 并明确告诉它滚动。

    例如:

    void ScrollToIndex(ListBox listBox, int index)
    {
        VirtualizingPanel panel = FindVisualChild<VirtualizingPanel>(listBox);
    
        panel.BringIndexIntoViewPublic(index);
    }
    
    static T FindVisualChild<T>(DependencyObject o) where T : class
    {
        T result = o as T;
    
        if (result != null)
        {
            return result;
        }
    
        int childCount = VisualTreeHelper.GetChildrenCount(o);
    
        for (int i = 0; i < childCount; i++)
        {
            result = FindVisualChild<T>(VisualTreeHelper.GetChild(o, i));
    
            if (result != null)
            {
                return result;
            }
        }
    
        return null;
    }
    

    我不太满意通过可视化树来搜索面板的需要,但是我不知道其他任何方法来获得它,也不知道在处理虚拟化面板时滚动到特定索引。