C# 如何管理与列表绑定的ListBox/CheckedListBox<&燃气轮机;用WinForms?

C# 如何管理与列表绑定的ListBox/CheckedListBox<&燃气轮机;用WinForms?,c#,winforms,list,data-binding,listbox,C#,Winforms,List,Data Binding,Listbox,如何将列表框或选中列表框与程序员定义对象的列表绑定?绑定后如何编辑数据?我可以通过哪个对象修改数据?如何在数据更改时更新列表框视图?如何在用户单击某个项目的复选框查看CheckedListBox时检索该项目复选框的选中状态 我想分享我所掌握的一些知识,因为我看到了很多关于这个主题的线索,但没有一条能够清楚地展示如何处理数据绑定。不要误解我的尝试,我只想展示一种轻松的方法 请随意评论。希望这会有帮助 在下文中,ListBox”与“ListBox”不同,后者是用于ListBox和CheckedLis

如何将
列表框
选中列表框
与程序员定义对象的
列表
绑定?绑定后如何编辑数据?我可以通过哪个对象修改数据?如何在数据更改时更新列表框视图?如何在用户单击某个项目的复选框查看
CheckedListBox
时检索该项目复选框的选中状态

我想分享我所掌握的一些知识,因为我看到了很多关于这个主题的线索,但没有一条能够清楚地展示如何处理数据绑定。不要误解我的尝试,我只想展示一种轻松的方法


请随意评论。希望这会有帮助

在下文中,
ListBox
”与“ListBox”不同,后者是用于
ListBox
CheckedListBox
的广义术语


首先,在
testForm\u Load
事件处理程序中完成绑定。必须知道要绑定的对象以及要在列表框中显示的属性/字段

((ListBox)m_checkedListBox).DataSource = m_underList;
((ListBox)m_checkedListBox).DisplayMember = "PropToDisplay";
m_underList.Add(new UserClass("Another example", 0, true));
据我所知,绑定的listbox的行为类似于只读单向(datasource=>listbox)镜像视图。我们只能通过处理底层数据对象或控件的事件机制(忘记
Items
&co)来影响列表框并检索其数据

对于
CheckListBox
,我们可以通过向
ItemCheck
事件添加
ItemCheckEventHandler
方法来检索选中的项,然后将其存储到属性的/字段的对象中

m_checkedListBox.ItemCheck += new ItemCheckEventHandler(this.ItemCheck);
但是我们不能定义数据源(基础列表)中内部选中项的状态,以在
复选框中显示为选中。
复选框
似乎不是设计成这样的

然后,可以通过底层列表随意添加或删除
Userclass
对象,或者调用任何您想要的方法。只是不关心列表框

((ListBox)m_checkedListBox).DataSource = m_underList;
((ListBox)m_checkedListBox).DisplayMember = "PropToDisplay";
m_underList.Add(new UserClass("Another example", 0, true));
最后,查看列表框的刷新。我看到许多文章谈到将
DataSource
设置为null,然后将其重新分配回以前的对象。我在寻找更好的方法(更好还是更漂亮?)。下面的方法非常简单

void refreshView(ListBox lb, object dataSource);
参考资料:

有关从列表框检索用户选择的补充信息,请访问

下面是一个简单示例的完整代码,该示例将
CheckedListBox
绑定、填充数据并清除。请注意,为了简单起见,我从listbox和数据列表都被排序的原则开始


UserClass.cs:用于存储显示/检查状态/隐藏数据的类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestForm
{
    class UserClass
    {
        private int m_underProp;

        // ctors
        public UserClass(string prop2Disp, int anotherObj, bool isChecked = false)
        {
            PropToDisplay = prop2Disp;
            IsChecked = isChecked;
            AnotherProp = anotherObj;
        }

        public UserClass()
        {
            PropToDisplay = string.Empty;
            IsChecked = false;
            AnotherProp = 0;
        }

        //  Property to be displayed in the listbox
        public string PropToDisplay
        {
            get;
            set;
        }

        //  For CheckedListBox only!
        //  Property used to store the check state of a listbox
        //  item when a user select it by clicking on his checkbox
        public bool IsChecked
        {
            get;
            set;
        }

        //  Anything you want
        public int AnotherProp
        {
            get
            {
                return m_underProp;
            }

            set
            {
                m_underProp = value;
                //  todo, processing...
            }
        }

        //  For monitoring
        public string ShowVarState()
        {
            StringBuilder str = new StringBuilder();

            str.AppendFormat("- PropToDisplay: {0}", PropToDisplay);
            str.AppendLine();
            str.AppendFormat("- IsChecked: {0}", IsChecked);
            str.AppendLine();
            str.AppendFormat("- AnotherProp: {0}", AnotherProp.ToString());

            return str.ToString();
        }
    }
}

TestForm.Designer.cs:表单的设计

namespace TestForm
{
    partial class testForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.m_checkedListBox = new System.Windows.Forms.CheckedListBox();
            this.m_toggle = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // m_checkedListBox
            // 
            this.m_checkedListBox.CheckOnClick = true;
            this.m_checkedListBox.FormattingEnabled = true;
            this.m_checkedListBox.Location = new System.Drawing.Point(13, 13);
            this.m_checkedListBox.Name = "m_checkedListBox";
            this.m_checkedListBox.Size = new System.Drawing.Size(171, 109);
            this.m_checkedListBox.TabIndex = 0;
            // 
            // m_toggle
            // 
            this.m_toggle.Location = new System.Drawing.Point(190, 53);
            this.m_toggle.Name = "m_toggle";
            this.m_toggle.Size = new System.Drawing.Size(75, 23);
            this.m_toggle.TabIndex = 1;
            this.m_toggle.Text = "Fill";
            this.m_toggle.UseVisualStyleBackColor = true;
            this.m_toggle.Click += new System.EventHandler(this.m_toggle_Click);
            // 
            // testForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(275, 135);
            this.Controls.Add(this.m_toggle);
            this.Controls.Add(this.m_checkedListBox);
            this.Name = "testForm";
            this.Text = "Form";
            this.Load += new System.EventHandler(this.testForm_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.CheckedListBox m_checkedListBox;
        private System.Windows.Forms.Button m_toggle;
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace TestForm
{
    public partial class testForm : Form
    {
        //  a List which will contain our external data. Named as the underlying list
        private List<UserClass> m_underList;

        public testForm()
        {
            InitializeComponent();

            m_underList = new List<UserClass> (3);
        }

        private void testForm_Load(object sender, EventArgs e)
        {
            //  Bind the CheckedListBox with the List
            //  The DataSource property is hidden so cast the object back to ListBox
            ((ListBox)m_checkedListBox).DataSource = m_underList;

            //  Tell which property/field to display in the CheckedListBox
            //  The DisplayMember property is hidden so cast the object back to ListBox
            ((ListBox)m_checkedListBox).DisplayMember = "PropToDisplay";

            /*
             * The CheckedListBox is now in "read-only" mode, that means you can't add/remove/edit
             * items from the listbox itself or edit the check states. You can't access
             * the underlying list through the listbox. Considers it as a unidirectionnal mirror
             * of the underlying list. The internal check state is disabled too, however
             * the ItemCheck event is still raised...
             */

            //  Manually set the ItemCheck event to set user defined objects
            m_checkedListBox.ItemCheck += new ItemCheckEventHandler(this.ItemCheck);
        }

        private void ItemCheck(object sender, ItemCheckEventArgs evnt)
        {
            if (sender == m_checkedListBox)
            {
                if (!m_checkedListBox.Sorted)
                {
                    //  Set internal object's flag to remember the checkbox state
                    m_underList[evnt.Index].IsChecked = (evnt.NewValue != CheckState.Unchecked);

                    //  Monitoring
                    Debug.WriteLine(m_underList[evnt.Index].ShowVarState());
                }
                else
                {
                    //  If sorted... DIY
                }
            }
        }

        private void m_toggle_Click(object sender, EventArgs e)
        {
            if (sender == m_toggle)
            {
                if (m_toggle.Text == "Fill")
                {
                    //  Fill the checkedListBox with some data
                    //  Populate the list with external data.
                    m_underList.Add(new UserClass("See? It works!", 42));
                    m_underList.Add(new UserClass("Another example", 0, true));
                    m_underList.Add(new UserClass("...", -7));
                    m_toggle.Text = "Clear";
                }
                else
                {
                    //  Empty the checkedListBox
                    m_underList.Clear();
                    m_toggle.Text = "Fill";
                }

                //  Refresh view
                //  Remember CheckedListBox inherit from ListBox
                refreshView(m_checkedListBox, m_underList);
            }
        }

        //  Magic piece of code which refresh the listbox view
        void refreshView(ListBox lb, object dataSource)
        {
            CurrencyManager cm = (CurrencyManager)lb.BindingContext[dataSource];
            cm.Refresh();
        }
    }
}
名称空间测试表单
{
部分类测试表单
{
/// 
///必需的设计器变量。
/// 
private System.ComponentModel.IContainer components=null;
/// 
///清理所有正在使用的资源。
/// 
///如果应释放托管资源,则为true;否则为false。
受保护的覆盖无效处置(布尔处置)
{
if(处理和(组件!=null))
{
组件。Dispose();
}
基地。处置(处置);
}
#区域Windows窗体设计器生成的代码
/// 
///设计器支持所需的方法-不修改
///此方法的内容与代码编辑器一起使用。
/// 
私有void InitializeComponent()
{
this.m_checkedListBox=new System.Windows.Forms.checkedListBox();
this.m_toggle=new System.Windows.Forms.Button();
这个.SuspendLayout();
// 
//m_checkedListBox
// 
this.m_checkedListBox.CheckOnClick=true;
this.m_checkedListBox.FormattingEnabled=true;
this.m_checkedListBox.Location=新系统.图纸.点(13,13);
this.m_checkedListBox.Name=“m_checkedListBox”;
this.m_checkedListBox.Size=新系统图纸尺寸(171109);
this.m_checkedListBox.TabIndex=0;
// 
//m_开关
// 
this.m_toggle.Location=新系统图纸点(190,53);
this.m_toggle.Name=“m_toggle”;
this.m_toggle.Size=新系统图纸尺寸(75,23);
this.m_toggle.TabIndex=1;
此.m_toggle.Text=“Fill”;
this.m_toggle.UseVisualStyleBackColor=true;
this.m\u toggle.Click+=new System.EventHandler(this.m\u toggle\u Click);
// 
//测试表格
// 
此.AutoScaleDimensions=新系统.Drawing.SizeF(6F,13F);
this.AutoScaleMode=System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize=新系统图纸尺寸(275135);
this.Controls.Add(this.m_切换);
this.Controls.Add(this.m_checkedListBox);
this.Name=“testForm”;
this.Text=“Form”;
this.Load+=new System.EventHandler(this.testForm\u Load);
此选项为.resume布局(false);
}
#端区
private System.Windows.Forms.CheckedListBox m_CheckedListBox;
private System.Windows.Forms.Button m_切换;
}
}

TestForm.cs:表单的行为

namespace TestForm
{
    partial class testForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.m_checkedListBox = new System.Windows.Forms.CheckedListBox();
            this.m_toggle = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // m_checkedListBox
            // 
            this.m_checkedListBox.CheckOnClick = true;
            this.m_checkedListBox.FormattingEnabled = true;
            this.m_checkedListBox.Location = new System.Drawing.Point(13, 13);
            this.m_checkedListBox.Name = "m_checkedListBox";
            this.m_checkedListBox.Size = new System.Drawing.Size(171, 109);
            this.m_checkedListBox.TabIndex = 0;
            // 
            // m_toggle
            // 
            this.m_toggle.Location = new System.Drawing.Point(190, 53);
            this.m_toggle.Name = "m_toggle";
            this.m_toggle.Size = new System.Drawing.Size(75, 23);
            this.m_toggle.TabIndex = 1;
            this.m_toggle.Text = "Fill";
            this.m_toggle.UseVisualStyleBackColor = true;
            this.m_toggle.Click += new System.EventHandler(this.m_toggle_Click);
            // 
            // testForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(275, 135);
            this.Controls.Add(this.m_toggle);
            this.Controls.Add(this.m_checkedListBox);
            this.Name = "testForm";
            this.Text = "Form";
            this.Load += new System.EventHandler(this.testForm_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.CheckedListBox m_checkedListBox;
        private System.Windows.Forms.Button m_toggle;
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace TestForm
{
    public partial class testForm : Form
    {
        //  a List which will contain our external data. Named as the underlying list
        private List<UserClass> m_underList;

        public testForm()
        {
            InitializeComponent();

            m_underList = new List<UserClass> (3);
        }

        private void testForm_Load(object sender, EventArgs e)
        {
            //  Bind the CheckedListBox with the List
            //  The DataSource property is hidden so cast the object back to ListBox
            ((ListBox)m_checkedListBox).DataSource = m_underList;

            //  Tell which property/field to display in the CheckedListBox
            //  The DisplayMember property is hidden so cast the object back to ListBox
            ((ListBox)m_checkedListBox).DisplayMember = "PropToDisplay";

            /*
             * The CheckedListBox is now in "read-only" mode, that means you can't add/remove/edit
             * items from the listbox itself or edit the check states. You can't access
             * the underlying list through the listbox. Considers it as a unidirectionnal mirror
             * of the underlying list. The internal check state is disabled too, however
             * the ItemCheck event is still raised...
             */

            //  Manually set the ItemCheck event to set user defined objects
            m_checkedListBox.ItemCheck += new ItemCheckEventHandler(this.ItemCheck);
        }

        private void ItemCheck(object sender, ItemCheckEventArgs evnt)
        {
            if (sender == m_checkedListBox)
            {
                if (!m_checkedListBox.Sorted)
                {
                    //  Set internal object's flag to remember the checkbox state
                    m_underList[evnt.Index].IsChecked = (evnt.NewValue != CheckState.Unchecked);

                    //  Monitoring
                    Debug.WriteLine(m_underList[evnt.Index].ShowVarState());
                }
                else
                {
                    //  If sorted... DIY
                }
            }
        }

        private void m_toggle_Click(object sender, EventArgs e)
        {
            if (sender == m_toggle)
            {
                if (m_toggle.Text == "Fill")
                {
                    //  Fill the checkedListBox with some data
                    //  Populate the list with external data.
                    m_underList.Add(new UserClass("See? It works!", 42));
                    m_underList.Add(new UserClass("Another example", 0, true));
                    m_underList.Add(new UserClass("...", -7));
                    m_toggle.Text = "Clear";
                }
                else
                {
                    //  Empty the checkedListBox
                    m_underList.Clear();
                    m_toggle.Text = "Fill";
                }

                //  Refresh view
                //  Remember CheckedListBox inherit from ListBox
                refreshView(m_checkedListBox, m_underList);
            }
        }

        //  Magic piece of code which refresh the listbox view
        void refreshView(ListBox lb, object dataSource)
        {
            CurrencyManager cm = (CurrencyManager)lb.BindingContext[dataSource];
            cm.Refresh();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
使用系统诊断;
使用System.IO;
命名空间测试表单
{
公共部分类testForm:Form
{
//包含外部数据的列表。命名为基础列表
私有列表m_参考列表;
公共测试表单()