我有两种形式:form1和form2。
form1包含button1
和listbox1
,form2包含button2
和checkedlistbox1
。
点击button1
时必须打开form2
并检查checkedlistbox1
的项目。然后点击button2
,以便form2
关闭,listbox1
必须显示来自checkedlistbox1
的已检查项目。但是我无法将选中的项目从checkedlistbox1
复制到listbox1
。我该怎么办,请帮忙。
答案 0 :(得分:3)
因此,我们首先将此属性添加到Form2
。这将是沟通的核心:
public IEnumerable<string> CheckedItems
{
get
{
//If the items aren't strings `Cast` them to the appropirate type and
//optionally use `Select` to convert them to what you want to expose publicly.
return checkedListBox1.SelectedItems
.OfType<string>();
}
set
{
var itemsToSelect = new HashSet<string>(value);
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
checkedListBox1.SetSelected(i,
itemsToSelect.Contains(checkedListBox1.Items[i]));
}
}
}
这样我们就可以从其他表单中设置所选项目(可以为项目值使用string
以外的其他内容),或者从此表单中获取所选项目。
然后在Form1
我们可以做到:
private void button1_Click(object sender, EventArgs e)
{
Form2 other = new Form2();
other.CheckedItems = listBox1.SelectedItems.OfType<string>();
other.FormClosed += (_, args) => setSelectedListboxItems(other.CheckedItems);
other.Show();
}
private void setSelectedListboxItems(IEnumerable<string> enumerable)
{
var itemsToSelect = new HashSet<string>(enumerable);
for (int i = 0; i < listBox1.Items.Count; i++)
{
listBox1.SetSelected(i , itemsToSelect.Contains(listBox1.Items[i]));
}
}
当我们单击按钮时,我们创建第二个表单的实例,设置它的选定索引,向FormClosed
事件添加处理程序以使用新选择更新列表框,然后显示表单。您会注意到,设置某些ListBox
项的实现方式与CheckedItems
的{{1}}方法完全相同。如果你发现自己这么做了很多,可以考虑将它重构为更通用的方法。