代码之家  ›  专栏  ›  技术社区  ›  George Sealy

Silverlight-如何以编程方式选择数据绑定列表框中的项?

  •  0
  • George Sealy  · 技术社区  · 16 年前

    我有一个列表框(AvailableDeviceListBox),它是使用Silverlight 3中的数据绑定填充的。绑定到类型为的对象集合 设备 . 它被设置为允许多个选择,这一切都很好。

    设备 对象,而不是ListBoxItem对象,因此我无法在列表框中选择/取消选择所需的项目。

    有人能提供一些建议吗?

    2 回复  |  直到 16 年前
        1
  •  2
  •   serge_gubenko    16 年前

    SelectedItems 属性来添加所有需要选择的项(如果需要全选,我猜它们都是)。下面是一个对我来说效果很好的小例子:

    // 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);
    

    希望这有帮助,谢谢

        2
  •  0
  •   Bryant    16 年前

    Xaml

    <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);
        }
    }
    
    推荐文章