Silverlight-如何以编程方式选择数据绑定列表框中的项?
我有一个列表框(AvailableDeviceListBox),它是使用Silverlight 3中的数据绑定填充的。绑定到DeviceTo类型的对象集合。它被设置为允许多个选择,这一切都很好 但是,我正在尝试让“全选”按钮正常工作,如果我遍历AvailableDeviceListBox.Items集合,我将返回DeviceTo对象,而不是ListBoxItem对象,因此我无法选择/取消选择列表框中所需的项目Silverlight-如何以编程方式选择数据绑定列表框中的项?,silverlight,listbox,data-binding,Silverlight,Listbox,Data Binding,我有一个列表框(AvailableDeviceListBox),它是使用Silverlight 3中的数据绑定填充的。绑定到DeviceTo类型的对象集合。它被设置为允许多个选择,这一切都很好 但是,我正在尝试让“全选”按钮正常工作,如果我遍历AvailableDeviceListBox.Items集合,我将返回DeviceTo对象,而不是ListBoxItem对象,因此我无法选择/取消选择列表框中所需的项目 有人能提供任何建议吗?如果我正确理解了您的问题,您需要使用列表框的属性添加所有需要选择
有人能提供任何建议吗?如果我正确理解了您的问题,您需要使用列表框的属性添加所有需要选择的项目(如果您需要全部选择,我猜所有项目都可以)。下面是一个对我来说效果很好的小例子:
// 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);
//创建DeviceTo对象的集合
List listItems=新列表();
添加(新设备到(“test0”);
添加(新设备到(“测试1”);
添加(新设备到(“测试2”);
//将列表框绑定到集合
testListBox.ItemsSource=listItems;
//选择所有项目
foreach(listItems中的DeviceTo项)
testListBox.SelectedItems.Add(项);
希望这能有所帮助,这里有一个快速的方法: Xaml
谢谢大家的回答-我已经看到SelectedItems是只读的,没有意识到我可以使用Add()。现在效果很好,谢谢!
<StackPanel x:Name="LayoutRoot" Background="White">
<ListBox x:Name="list" SelectionMode="Multiple" />
<Button Content="Select All" Width="100" Click="Button_Click" />
</StackPanel>
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);
}
}