使用 C# 选择列表框中的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/665273/
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
Selecting items in a listbox using C#
提问by Anand Shah
I am using two ListBox controls in my WPF window that are identical (identical = ItemSource
of both the ListBox is same and so they look same) and the selection mode on both the ListBoxes is set to Multiple.
我在 WPF 窗口中使用了两个相同的 ListBox 控件(两个 ListBox 的相同 =ItemSource
相同,因此它们看起来相同)并且两个 ListBox 上的选择模式都设置为 Multiple。
Lets call the ListBoxes LB1
and LB2
for the time being, now when I click an item in LB1
, I want the same item in LB2
to get selected automatically i.e if I select 3 items in LB1 using either Shift+Clickor Ctrl+Clickthe same items in LB2
get selected.
让我们调用列表框LB1
和LB2
暂时,现在当我点击一个项目LB1
,我想在同一个项目LB2
得到自动选择,即如果我选择LB1 3项使用任一Shift+Click或Ctrl+Click在同一个项目LB2
得到选择。
Have dug the Listbox properties like SelectedItems
, SelectedIndex
etc but no luck.
挖列表框的属性,如SelectedItems
,SelectedIndex
等,但没有运气。
采纳答案by Arcturus
Place a SelectionChanged event on your first listbox
在您的第一个列表框上放置一个 SelectionChanged 事件
LB1.SelectionChanged += LB1_SelectionChanged;
Then implement the SelectionChanged method like so:
然后像这样实现 SelectionChanged 方法:
void LB1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LB2.SelectedItems.Clear();
foreach(var selected in LB1.SelectedItems)
{
LB2.SelectedItems.Add(selected);
}
}
回答by RvdK
Did you try SetSelected?
你试过 SetSelected 吗?
listBox2.SetSelected(1, True)
You can use it like this
你可以像这样使用它
private void DoLB2Selection()
{
// Loop through all items the ListBox.
for (int x = 0; x < listBox1.Items.Count; x++)
{
// Determine if the item is selected.
if(listBox1.GetSelected(x) == true)
// Deselect all items that are selected.
listBox2.SetSelected(x,true);
}
use the selected items from LB1 as a index in LB2
使用从 LB1 中选择的项目作为 LB2 中的索引