C#:自定义事件

来源:互联网 发布:南京高新区网络问政 编辑:程序博客网 时间:2024/05/17 18:46

1.实例

这里写图片描述

需求:自定义控件中有勾选则"下一步"按钮可用,否则不可用

2.代码

    //自定义控件    public partial class Selector : UserControl    {        public delegate void MyDg(bool enable);        public event MyDg MyTestDg;          private List<string> _initialItems;        public List<string> InitialItems        {            set {                this._initialItems = value;                LoadDate();            }        }        public Selector()        {            InitializeComponent();        }        private void LoadDate()        {            this.listBoxSelector.Items.Clear();            if (this._initialItems == null || this._initialItems.Count <= 0) return;            this._initialItems.ForEach(temp => this.listBoxSelector.Items.Add(new ListBoxItem() { Text = temp }));        }        private void listBoxSelector_ItemClick(object sender, EventArgs e)        {            ListBoxItem item = sender as ListBoxItem;            if (item == null) return;            item.CheckState = (item.CheckState == CheckState.Checked) ? CheckState.Unchecked : CheckState.Checked;            //调用事件            if (MyTestDg != null)                MyTestDg.Invoke(IsAllUnCheck());        }        private bool IsAllUnCheck()        {            if (this.listBoxSelector.Items.Count <= 0) return false;            bool flag = true;            foreach (ListBoxItem item in this.listBoxSelector.Items)            {                if (item.CheckState == CheckState.Checked)                {                    flag = false;                    break;                }                else if (item.CheckState == CheckState.Unchecked)                    flag = true;            }            return flag;        }
    public partial class FrmMyEvent : Office2007Form    {        public FrmMyEvent()        {            InitializeComponent();            this.EnableGlass = false;        }        private void FrmMyEvent_Load(object sender, EventArgs e)        {            this.btnNext.Enabled = false;            List<string> tempItems = new List<string>() { "C#", "Java", "C", "C++","VB"};            this.selector.InitialItems = tempItems;            //注册事假            this.selector.MyTestDg += Selector_MyTestDg;        }        private void Selector_MyTestDg(bool enable)        {            this.btnNext.Enabled = !enable;        }    }

3.结果

这里写图片描述
这里写图片描述

0 0
原创粉丝点击