How can I set different Tooltip text for each item in a listbox?

前端 未结 7 1172
情话喂你
情话喂你 2020-12-01 07:57

I have a listbox that is databound to a Collection of objects. The listbox is configured to display an identifier property of each object. I would like to show a tooltip w

7条回答
  •  时光取名叫无心
    2020-12-01 08:32

    You can use this simple code that uses the onMouseMove event of ListBox in WinForms:

    private void ListBoxOnMouseMove(object sender, MouseEventArgs mouseEventArgs)
    {
            var listbox = sender as ListBox;
            if (listbox == null) return;
    
            // set tool tip for listbox
            var strTip = string.Empty;
            var index = listbox.IndexFromPoint(mouseEventArgs.Location);
    
            if ((index >= 0) && (index < listbox.Items.Count))
                strTip = listbox.Items[index].ToString();
    
            if (_toolTip.GetToolTip(listbox) != strTip)
            {
                _toolTip.SetToolTip(listbox, strTip);
            }
    }
    

    Of course you will have to init the ToolTip object in the constructor or some init function:

    _toolTip = new ToolTip
    {
                AutoPopDelay = 5000,
                InitialDelay = 1000,
                ReshowDelay = 500,
                ShowAlways = true
    };
    

    Enjoy!

提交回复
热议问题