【问题标题】:Winforms CheckedListBox element bound to window titleWinforms CheckedListBox 元素绑定到窗口标题
【发布时间】:2014-02-22 00:35:57
【问题描述】:

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

目前我知道我可以为我的CheckedListBox 创建一个DataSource(字符串列表):

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

但这会使文本变成静态的——当窗口的标题改变时它不会改变。我该如何处理?

【问题讨论】:

    标签: c# winforms binding


    【解决方案1】:

    您可以创建另一种类型的集合(如字典)并将窗口句柄存储为键,将文本存储为值。当表单的标题发生变化时,您可以找到您的值并进行更新。

        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";
        }
    

    【讨论】:

      【解决方案2】:

      我找到了办法。

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

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

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

      【讨论】:

        最近更新 更多