views:

370

answers:

2

Hi all,

I have a ListBox (AvailableDevicesListBox), which is populated using data-binding in Silverlight 3. The binding is to a collection of objects of type DeviceDTO. It is set up to allow multiple selections, and this all works fine.

However, I'm trying to get a 'Select All' button working, and if I iterate through the AvailableDevicesListBox.Items collection, I'm returned DeviceDTO objects, not ListBoxItem objects, so I have no way of selecting / deselecting the items in the list box that I want.

Can anyone offer any suggestions?

+1  A: 

If I'm understanding your question correctly you would need to use SelectedItems property of the ListBox to add all the items you need to select (I guess all of them if you need to select all). Below is a small example which worked fine for me:

// create collection of DeviceDTO objects
List<DeviceDTO> listItems = new List<DeviceDTO>();

listItems.Add(new DeviceDTO("test0"));
listItems.Add(new DeviceDTO("test1"));
listItems.Add(new DeviceDTO("test2"));

// bind listbox to the collection
testListBox.ItemsSource = listItems;

// select all items
foreach (DeviceDTO item in listItems)
    testListBox.SelectedItems.Add(item);

hope this helps, regards

serge_gubenko
A: 

Here is a quick way I did this:

Xaml

<StackPanel x:Name="LayoutRoot" Background="White">
    <ListBox x:Name="list" SelectionMode="Multiple" />
    <Button Content="Select All" Width="100" Click="Button_Click" />
</StackPanel>

Code public MainPage() { InitializeComponent();

var items = new List<string>(){"one", "two", "three", "four", "five"};
list.ItemsSource = items;

}

private void Button_Click(object sender, RoutedEventArgs e)
{
    foreach (var item in list.ItemsSource)
    {
        list.SelectedItems.Add(item);
    }
}
Bryant