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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1069577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:30:24  来源:igfitidea点击:

Select item programmatically in WPF ListView

c#.netwpflistviewselecteditem

提问by Paul Prewett

I'm unable to figure out how to select an item programmatically in a ListView.

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

I'm attempting to use the listview's ItemContainerGenerator, but it just doesn't seem to work. For example, obj is null after the following operation:

我正在尝试使用列表视图的 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]);

I've tried (based on suggestions seen here and other places) to use the ItemContainerGenerator's StatusChanged event, but to no avail. The event never fires. For example:

我尝试过(基于此处和其他地方的建议)使用 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]);
}

The crux of this whole thing is that I simply want to pre-select a few of the items in my ListView.

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

In the interest of not leaving anything out, the ListView uses some templating and Drag/Drop functionality, so I'm including the XAML here. Essentially, this template makes each item a textbox with some text - and when any item is selected, the checkbox is checked. And each item also gets a little glyph underneath it to insert new items (and this all works fine):

为了不遗漏任何内容,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"/>

So what am I missing? How do I programmatically select one or more of the items in the ListView?

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

采纳答案by Kent Boogaart

Bind the IsSelectedproperty of the ListViewItemto a property on your model. Then, you need only work with your model rather than worrying about the intricacies of the UI, which includes potential hazards around container virtualization.

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

For example:

例如:

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

Now, just work with your model's IsGroovyproperty to select/deselect items in the ListView.

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

回答by Will Eddins

Here would be my best guess, which would be a much simpler method for selection. Since I'm not sure what you're selecting on, here's a generic example:

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

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);
}

What I'm used to seeing is a settable SelectedItem, but I see you can't set or add to this, but hopefully this method works as a replacement.

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

回答by Ahmad

Where 'this' is the ListView instance. This will not only change the selection, but also set the focus on the newly selected item.

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