在WPF ListView中以编程方式选择项目

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

我正在尝试使用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使用了一些模板和拖放function,所以我在这里包含了XAML。 本质上,此模板使每个项目成为包含一些文本的文本框 – 当选择任何项目时,将选中该复选框。 并且每个项目下面都会有一个小字形来插入新项目(这一切都很好):

       ...  

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

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

例如:

      

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

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

 var indices = new List(); 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,但是我看到你无法设置或添加它,但希望这个方法可以替代它。

其中’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(); } }