C# 如何在列表框 wpf 中获取多个选定项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19123305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:09:48  来源:igfitidea点击:

How to get multiple selected items in listbox wpf?

c#.netwpflistbox

提问by

I am confused on how to retrieve multi selected values from listbox in wpf.

我对如何从 wpf 中的列表框中检索多选值感到困惑。

In XAML I have the following listbox with selection mode multiple.

在 XAML 中,我有以下带有多个选择模式的列表框。

 <ListBox Height="100" HorizontalAlignment="Left" Margin="139,207,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" SelectionChanged="listBox1_SelectionChanged" SelectionMode="Multiple" />    

 <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="319,220,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />

How do I check in foreach loop now?

我现在如何检查 foreach 循环?

        foreach (ListItem li in listBox1.Items)
        {
                ?? // how to check li is selected or not
        }

采纳答案by LPL

You will find them in ListBox.SelectedItems.

您将在ListBox.SelectedItems 中找到它们。

foreach (var item in listBox1.SelectedItems)
{

}

回答by Barak Rosenfeld

another example

另一个例子

int j = 0;
for (int i = 0; i < lbItems.Items.Count; i++)
{
   if (lbItems.Items[i] == lbItems.SelectedItems[0])
   j++;
}
MessageBox.Show(lbItems.Items.IndexOf(lbItems.SelectedItems[0]).ToString()
+ string.Format("\r\nThere are {0} occurences of this object in this list",j) )