【问题标题】:changing selected itms color in a listbox更改列表框中选定的项目颜色
【发布时间】:2009-08-07 09:39:17
【问题描述】:

我想从列表框控件中更改所选项目的颜色如何做到这一点 在windows(Winforms)中

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    据我所知,如果您想这样做,您需要创建 ListBox.DrawMode OwnerDrawFixed 并向 DrawItem 方法添加一个事件处理程序。

    这样的事情可能会做你想做的事:

        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);
            }
        }
    

    希望对你有帮助 詹姆斯

    【讨论】:

    • +1 - 这也与我们的实现非常相似。
    【解决方案2】:

    假设您正在使用 WinForms:

    大多数控件都有 BackColor 和 BorderColor 属性。您可以将Color 对象添加到列表框(颜色名称应显示为Color.ToString() 返回名称),然后使用listbox.SelectedItems[0] 获取颜色并更新其他控件的BackColor 等。

    【讨论】:

    • 列表框项的类型为 System.Object,无背景。
    • 哦。我认为 OP 是在询问如何根据列表框中的选择来更改控件的颜色。我没有意识到他希望每个列表框项目本身都有不同的颜色。那好吧。来之不易,去之亦然。
    猜你喜欢
    • 2011-01-09
    • 2011-07-28
    • 2011-07-01
    • 2013-05-03
    • 1970-01-01
    • 2011-10-17
    • 2016-08-23
    • 1970-01-01
    相关资源
    最近更新 更多