【问题标题】:How to access to checked items from another form?如何从另一个表单访问已检查的项目?
【发布时间】:2012-11-21 19:31:05
【问题描述】:

我有两种形式:form1 和 form2。

form1 包含button1listbox1,form2 包含button2checkedlistbox1

点击button1时必须打开form2并检查checkedlistbox1的项目。然后单击button2,这样form2 关闭,listbox1 必须显示来自checkedlistbox1 的选中项目。但是我无法将检查项目从checkedlistbox1 复制到listbox1 的问题。我该怎么做,请帮忙。

【问题讨论】:

    标签: c#


    【解决方案1】:

    所以我们首先将此属性添加到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 项目的方法的实现与CheckedItemsset 方法中的模式完全相同。如果您发现自己经常这样做,请考虑将其重构为更通用的方法。

    【讨论】:

    • @lazyberezovsky 请不要仅仅为了遵循您习惯的编码约定而编辑其他用户答案中的代码。如果它有问题,那就不同了,但是仅仅为了使用您喜欢的命名约定而进行编辑并不是建议编辑的预期目的。
    • 我以为你打错了,因为_ 是我以前从未见过的名字
    • @lazyberezovsky 下划线 _ 是 C# 中变量的完全有效标识符。按照惯例,它用于表示 lambda 的未使用参数。它只是为了确保它与代表的签名相匹配。如果我要实际使用它(我永远不会,因为我已经有一个表示另一种形式的强类型变量)我会给它一个不同的名字。
    • args 也是未使用的参数
    • 神圣的代码,蝙蝠侠!非常酷地使用“OfType”和 lambdas。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2023-03-06
    • 2013-03-28
    • 2022-12-28
    • 1970-01-01
    相关资源
    最近更新 更多