• 如何为标准的ListBox添加ItemClick事件


    今天在项目中遇到了一个小问题,需要给ListBox添加ItemClick事件,很简单:

     public class MyListBox:ListBox
        {
            private static readonly object EventItemClick = new object();
            public event EventHandler<ListBoxItemEventArgs> ItemClick
            {
                add
                {
                    Events.AddHandler(EventItemClick, value);
                }
                remove
                {
                    Events.RemoveHandler(EventItemClick, value);
                }
            }      
          
           
            protected virtual void OnItemClick(ListBoxItemEventArgs e)
            {
                EventHandler<ListBoxItemEventArgs> handler = (EventHandler<ListBoxItemEventArgs>)this.Events[EventItemClick];
                if (handler != null)
                {
                    handler(this, e);
                }
            }

            protected override void OnClick(EventArgs e)
            {
                base.OnClick(e);
                for (int i = 0; i < this.Items.Count; i++)
                {
                    bool flag = this.GetItemRectangle(i).Contains(this.PointToClient(Control.MousePosition));
                    if (flag)
                    {
                        ListBoxItemEventArgs args = new ListBoxItemEventArgs(i);
                        OnItemClick(args);
                        break;
                    }
                }
            }
        }

        public class ListBoxItemEventArgs : EventArgs
        {
            private int _listBoxItem;

            public ListBoxItemEventArgs(int listBoxItem)
            {
                _listBoxItem = listBoxItem;
            }

            public int ListBoxItem
            {
                get
                {
                    return _listBoxItem;
                }
            }
        }

  • 相关阅读:
    Leetcode 剑指 Offer 27(二叉树的镜像)
    Leetcode 1022从根到叶的二进制之和
    Leetcode 993二叉树的堂兄弟节点
    Leetcode 965单值二叉树
    Leetcode 938 二叉搜索树的范围和
    hdu 2082 找单词
    母函数模板
    hdu 1398 Square Coins
    hdu 1085 Holding Bin-Laden Captive!
    hdu 1028 Ignatius and the Princess III
  • 原文地址:https://www.cnblogs.com/xixifusigao/p/1518530.html
Copyright © 2020-2023  润新知