Winforms CheckedListBox 元素绑定到窗口标题



我需要创建一个窗口来管理打开的对话框(隐藏、显示、添加新对话框、关闭对话框)。我希望CheckedListBox的每个记录都是窗口的标题(someFormObject.Text)。如果标题发生变化,我也想更改记录。

至于现在我知道我可以为我的CheckedListBox创建一个DataSource(字符串列表):

_listRecords = new BindingSource();
checkedListBox1.DataSource = _listRecords;
_listRecords.Add(newForm.Text);

但这会使文本成为静态文本 - 当窗口标题更改时,它不会更改。我该如何处理?

可以创建其他类型的集合(如字典),并将窗口句柄存储为键,将文本存储为值。当表单的标题更改时,您可以找到您的值并对其进行更新。

    public Dictionary<IntPtr, string> forms = new Dictionary<IntPtr, string>();
    private void button1_Click(object sender, EventArgs e)
    {
        var newForm = new Form();
        newForm.Text = "New Form Text";
        forms.Add(newForm.Handle, newForm.Text);
        //look through our dictionary to find if the form exists
        //if it does, update the value, otherwise add a new entry
        if (forms.Keys.Contains(newForm.Handle))
            forms[newForm.Handle] = newForm.Text;
        else
            forms.Add(newForm.Handle, newForm.Text);
        RefreshDatasource();
    }
    private void RefreshDatasource()
    {
        checkedListBox1.DataSource = forms.ToList();
        checkedListBox1.DisplayMember = "Value";
    }

我找到了一种方法。

您实际上需要添加实际的form,而不是记录中的string(因为您传递引用而不是值类型)。

private BindingList<Form> _activeWindows;
// constructor:
checkedListBox1.DataSource = _activeWindows;
checkedListBox1.DisplayMember = "Text";
// adding new element
_activeWindows.Add(newWindow);

绑定将自动更新所有内容。

最新更新