Select item programmatically in WPF ListView

In case you are not working with Bindings, this could also be a solution, just find the items in the source and add them to the SelectedItems property of your listview:

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

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.


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

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

Bind the IsSelected property of the ListViewItem to 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.

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 IsGroovy property to select/deselect items in the ListView.