【问题标题】:Select item programmatically in WPF ListView在 WPF ListView 中以编程方式选择项目
【发布时间】:2010-11-07 08:40:51
【问题描述】:

我无法弄清楚如何在 ListView 中以编程方式选择项目。

我正在尝试使用列表视图的 ItemContainerGenerator,但它似乎不起作用。例如,经过如下操作,obj为null:

//VariableList is derived from BindingList
m_VariableList = getVariableList();
lstVariable_Selected.ItemsSource = m_VariableList;
var obj = 
    lstVariable_Selected.ItemContainerGenerator.ContainerFromItem(m_VariableList[0]);

我已尝试(根据此处和其他地方看到的建议)使用 ItemContainerGenerator 的 StatusChanged 事件,但无济于事。该事件永远不会触发。例如:

m_VariableList = getVariableList();
lstVariable_Selected.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
lstVariable_Selected.ItemsSource = m_VariableList;

...

void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
    //This code never gets called
    var obj = lstVariable_Selected.ItemContainerGenerator.ContainerFromItem(m_VariableList[0]);
}

整个事情的关键是我只想在我的 ListView 中预先选择一些项目。

为了不遗漏任何内容,ListView 使用了一些模板和拖放功能,因此我将 XAML 包括在此处。本质上,这个模板使每个项目成为一个带有一些文本的文本框 - 当任何项目被选中时,复选框被选中。每个项目下面还有一个小字形来插入新项目(这一切都很好):

<DataTemplate x:Key="ItemDataTemplate_Variable">
<StackPanel>
    <CheckBox x:Name="checkbox"
        Content="{Binding Path=ListBoxDisplayName}"
        IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Path=IsSelected}" />
    <Image ToolTip="Insert Custom Variable" Source="..\..\Resources\Arrow_Right.gif" 
        HorizontalAlignment="Left" 
        MouseLeftButtonDown="OnInsertCustomVariable"
        Cursor="Hand" Margin="1, 0, 0, 2" Uid="{Binding Path=CmiOrder}" />
</StackPanel>
</DataTemplate>

...

<ListView Name="lstVariable_All" MinWidth="300" Margin="5"
   SelectionMode="Multiple"
   ItemTemplate="{StaticResource ItemDataTemplate_Variable}"
   SelectionChanged="lstVariable_All_SelectionChanged"
   wpfui:DragDropHelper.IsDropTarget="True" 
   wpfui:DragDropHelper.IsDragSource="True"
   wpfui:DragDropHelper.DragDropTemplate="{StaticResource ItemDataTemplate_Variable}"
       wpfui:DragDropHelper.ItemDropped="OnItemDropped"/>

那么我错过了什么?如何以编程方式选择 ListView 中的一项或多项?

【问题讨论】:

    标签: c# .net wpf listview selecteditem


    【解决方案1】:

    如果您不使用绑定,这也可能是一种解决方案,只需在源中找到项目并将它们添加到列表视图的 SelectedItems 属性中:

     lstRoomLights.ItemsSource = RoomLights;
     var selectedItems = RoomLights.Where(rl => rl.Name.Contains("foo")).ToList();
     selectedItems.ForEach(i => lstRoomLights.SelectedItems.Add(i));
    

    【讨论】:

      【解决方案2】:

      其中“this”是 ListView 实例。这不仅会改变选择,还会将焦点设置在新选择的项目上。

        private void MoveSelection(int level)
        {
           var newIndex = this.SelectedIndex + level;
           if (newIndex >= 0 && newIndex < this.Items.Count)
           {
              this.SelectedItem = this.Items[newIndex];
              this.UpdateLayout();
              ((ListViewItem)this.ItemContainerGenerator.ContainerFromIndex(newIndex)).Focus();
           }
        }
      

      【讨论】:

        【解决方案3】:

        ListViewItemIsSelected 属性绑定到模型上的属性。然后,您只需使用您的模型,而不必担心 UI 的复杂性,其中包括容器虚拟化的潜在危险。

        例如:

        <ListView>
            <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Setter Property="IsSelected" Value="{Binding IsGroovy}"/>
                </Style>
            </ListView.ItemContainerStyle>
        </ListView>
        

        现在,只需使用模型的 IsGroovy 属性来选择/取消选择 ListView 中的项目。

        【讨论】:

        • 当然。数据绑定。 WPF 中的所有问题不是都归结为数据绑定吗?谢谢,肯特。
        • 这是一个非常巧妙的解决方案,赞!
        • 请注意:此解决方案不适用于 Windows 应用商店应用。相反,您应该在后面的代码中设置绑定,如下所示:social.msdn.microsoft.com/Forums/windowsapps/en-US/…
        【解决方案4】:

        这是我最好的猜测,这将是一种更简单的选择方法。由于我不确定您选择的是什么,这里有一个通用示例:

        var indices = new List<int>();
        
        for(int i = 0; i < lstVariable_All.Items.Count; i++)
        {
          // If this item meets our selection criteria 
          if( lstVariable_All.Items[i].Text.Contains("foo") )
            indices.Add(i);
        }
        
        // Reset the selection and add the new items.
        lstVariable_All.SelectedIndices.Clear();
        
        foreach(int index in indices)
        {
          lstVariable_All.SelectedIndices.Add(index);
        }
        

        我习惯看到的是一个可设置的 SelectedItem,但我看到你不能设置或添加到它,但希望这种方法可以作为替代品。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-08
          • 2013-12-25
          • 1970-01-01
          • 2019-12-17
          • 2011-08-13
          • 2010-09-29
          相关资源
          最近更新 更多