Select item programmatically in WPF ListView

前端 未结 4 1694
[愿得一人]
[愿得一人] 2020-12-03 05:16

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

I\'m attempting to use the listview\'s ItemContainerGenerator, but it just doesn\'t s

相关标签:
4条回答
  • 2020-12-03 05:45

    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.

    0 讨论(0)
  • 2020-12-03 05:48

    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();
         }
      }
    
    0 讨论(0)
  • 2020-12-03 05:49

    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.

    0 讨论(0)
  • 2020-12-03 05:55

    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));
    
    0 讨论(0)
提交回复
热议问题