2

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 Answers 2

1

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]);
Sign up to request clarification or add additional context in comments.

Comments

0

Try calling

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.