【发布时间】:2012-07-03 22:31:47
【问题描述】:
我有一个包含重复项的 ListBox。据我所知,ListBox.SelectedItems 只会返回重复项的第一个实例,但是当我想对用户选择的所有项目执行操作时,这会导致问题。当我选择多个重复项并调用ListBox.SelectedItems.Count 时,我总是得到1。有没有办法获取所有项目的索引,无论它们是否唯一? (ListBox 模式设置为 Multiple)。
添加了演示代码,表明同一项目被视为重复。
Xaml:
<Grid x:Name="LayoutRoot" Background="White">
<ListBox Height="288" HorizontalAlignment="Left" Margin="12,0,0,0" Name="listBox1" VerticalAlignment="Top" Width="276" SelectionMode="Multiple" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="313,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
代码:
ObservableCollection<string> fruits = new ObservableCollection<string>();
fruits.Add("Apple");
fruits.Add("Pear");
fruits.Add("Orange");
fruits.Add("Apple");
listBox1.ItemsSource = fruits ;
我刚刚连接了一个按钮事件:
MessageBox.Show(listBox1.SelectedItems.Count.ToString());
选择最上面的Apple,点击按钮,会返回1。同时选择Apples,它将返回1。选择一个Apple 和Pear,它将返回2。
【问题讨论】:
-
ListBox.GetSelectedIndices() 可能吗?
-
谢谢,但 Silverlight 中不存在该方法。我的帖子被编辑为包含“asp.net”标签,但这不是 asp.net。
-
啊,我不知道silverlight。我在看 C# 标签。试试这个:stackoverflow.com/questions/3836313/…
-
不,不幸的是,foreach 循环只循环一次,因为它将任何重复项视为一项,而不是单独的项。
-
这真是奇怪,ListBox 关心的元素是一样的。你在哪里 SelectedItems 只返回第一个不同的元素?
标签: c# silverlight listbox duplicates selecteditem