changing selected itms color in a listbox

后端 未结 2 1001
暗喜
暗喜 2021-01-25 18:43

i want to change the color of a selected items from a list box control how to do that in windows(Winforms)

相关标签:
2条回答
  • 2021-01-25 19:19

    As far as I know if you want to do that you need to make the ListBox.DrawMode OwnerDrawFixed and add an event handler on to the DrawItem method.

    Something like this might do what you want:

        private void lstDrawItem(object sender, DrawItemEventArgs e)
        {
            ListBox lst = (ListBox)sender;
            e.DrawBackground();
            e.DrawFocusRectangle();
    
            DrawItemState st = DrawItemState.Selected ^ DrawItemState.Focus;
            Color col = ((e.State & st) == st) ? Color.Yellow : lst.BackColor;
    
            e.Graphics.DrawRectangle(new Pen(col), e.Bounds);
            e.Graphics.FillRectangle(new SolidBrush(col), e.Bounds);
            if (e.Index >= 0)
            {
                e.Graphics.DrawString(lst.Items[e.Index].ToString(), e.Font, new SolidBrush(lst.ForeColor), e.Bounds, StringFormat.GenericDefault);
            }
        }
    

    Hope it helps James

    0 讨论(0)
  • 2021-01-25 19:25

    Assuming you're working with WinForms:

    Most controls will have a BackColor and BorderColor property. You could add the Color objects to your listbox (the color name should be displayed as Color.ToString() returns the name), then use listbox.SelectedItems[0] to get the color and update the other controls' BackColor etc.

    0 讨论(0)
提交回复
热议问题