Programmatically selecting Items/Indexes in a ListBox

前端 未结 6 1895
情深已故
情深已故 2021-01-07 23:24

In WPF, I\'d like to set the selected indexes of a System.Windows.Controls.ListBox

I best way I\'ve found so far is to remove all the items from the control, insert

相关标签:
6条回答
  • 2021-01-07 23:51

    You can set multiple items as selected by using the SelectedItems collection. This isn't by index, but by what you have bound:

    foreach (var boundObject in objectsBoundToListBox)
    {
        ListBox.SelectedItems.Add(boundObject);
    }
    
    0 讨论(0)
  • 2021-01-07 23:51

    Thanks to mdm20. My case was actually checking a CheckBox within the ListBox, and this Dependency Property worked like a charm. I had to inherit my custom class from DependencyObject and implement the property

    public class ProjectListItem : DependencyObject{ 
    
        public Boolean IsChecked
        {
            get { return (Boolean)this.GetValue(CheckedProperty); }
            set { this.SetValue(CheckedProperty, value); }
        }
        public static readonly DependencyProperty CheckedProperty =
            DependencyProperty.Register("IsChecked", typeof(Boolean), typeof(ProjectListItem), 
                                        new PropertyMetadata(false));
    }
    
    0 讨论(0)
  • 2021-01-07 23:54

    You have to do this:

    ListBoxObject.SelectedItem = ListBoxObject.Items.GetItemAt(itemIndex);
    

    Where itemIndex would be the item you want to select. If you want to select multiple items, you need to use the ListBox.SelectedIndexCollection property.

    0 讨论(0)
  • 2021-01-08 00:00

    One way you can do this is to add a Selected field to your data object. Then you need to overide the default listboxitem style and bind the isselected property to the Selected property in your object. Then you just need to go through your data items and update the Selected value.

    If you don't implement that Selected property as a dependency property, you need your class to implented the INotifyPropertyChanged interface and raise the propertychanged event when you set the value.

    0 讨论(0)
  • 2021-01-08 00:15

    how to programmatically select multiple items in listbox in wpf

    foreach (var boundObject in objectsBoundToListBox)
    {
        ListBox.SelectedItems.Add(boundObject);
    }
    
    0 讨论(0)
  • 2021-01-08 00:16

    You can do this for multiple sections:

    ListBoxObject.SelectedItems.Add(ListBoxObject.Items.GetItemAt(i));
    

    Where i is the item index.

    0 讨论(0)
提交回复
热议问题