2
votes

I have a listbox with multiple items in it (20). I often need to select 4 of them. Instead of clicking on each item in the list box to select it, I would like to just click a button beside the listbox and have it select the 4 items.

<ListBox Name="lbExample" SelectionMode="Multiple">
    <ListBoxItem>a</ListBoxItem>
    <ListBoxItem>b</ListBoxItem>
    <ListBoxItem>c</ListBoxItem>
    <ListBoxItem>d</ListBoxItem>
    <ListBoxItem>e</ListBoxItem>
    <ListBoxItem>f</ListBoxItem>
    <ListBoxItem>g</ListBoxItem>
    <ListBoxItem>h</ListBoxItem>
    <ListBoxItem>i</ListBoxItem>
    <ListBoxItem>j</ListBoxItem>
    ...
</ListBox>

<Button Name="btnSelectGroupOne" Click="btnSelectGroupOne_Click" Content="Group One"></Button>

I have tried the following (trying to select items by Index):

private void btnSelectGroupOne_Click(object sender, RoutedEventArgs e)
{
    lbExample.SelectedItems.Add(0);
    lbExample.SelectedItems.Add(1);
    lbExample.SelectedItems.Add(2);
    lbExample.SelectedItems.Add(3);
}

I have also tried by string:

private void btnSelectGroupOne_Click(object sender, RoutedEventArgs e)
{
    lbExample.SelectedItems.Add("a");
    lbExample.SelectedItems.Add("b");
    lbExample.SelectedItems.Add("c");
    lbExample.SelectedItems.Add("d");
}

When I try either of these nothing is highlighted in the listbox.

2

2 Answers

1
votes

You need to pass the Item of the listbox in Add() method. You can do it like:

lbExample.SelectedItems.Add(lbExample.Items[0]);
lbExample.SelectedItems.Add(lbExample.Items[1]);
lbExample.SelectedItems.Add(lbExample.Items[2]);
lbExample.SelectedItems.Add(lbExample.Items[3]);
0
votes

Try calling

lbExample.SetSelectedItems(new List<string>{lbExample.Items[0]});