【问题标题】:Focus color remains after item is selected选择项目后焦点颜色保持不变
【发布时间】:2016-02-16 13:44:52
【问题描述】:

我制作了自己的 ComboBox 控件,以便使用具有自定义背景和前景色的项目。 ComboBox 也定义为 DropDownList。

public class CustomComboBox : ComboBox
{
    public CustomComboBox()
    {
        DrawMode = DrawMode.OwnerDrawVariable;
        DropDownStyle = ComboBoxStyle.DropDownList;
        FlatStyle = FlatStyle.Flat;
    }

    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        base.OnDrawItem(e);
        e.DrawBackground();
        var item = ((ResultColor)Items[e.Index]);

        e.Graphics.FillRectangle(item.BackgroundColor, e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);
        e.Graphics.DrawString(item.Name, Font, item.Color, e.Bounds.X, e.Bounds.Y);
        e.DrawFocusRectangle();
    }
}

如果重要的话,我的 ResultColor 类如下:

public class ResultColor
{
    public ResultColor(int id, string name, Brush color, Brush backgroundColor)
    {
        Id = id;
        Name = name;
        Color = color;
        BackgroundColor = backgroundColor;
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public Brush Color { get; set; }
    public Brush BackgroundColor { get; set; }

    public override string ToString()
    {
        return Name;
    }
}

我遇到的最初问题是,当鼠标悬停在聚焦的项目上时,列表中没有颜色。

进一步环顾四周,我发现我可以使用e.State 来检查当前的项目状态并更改颜色,所以现在我这样做了:

var brush = (e.State & DrawItemState.Focus) == DrawItemState.Focus ?
             Brushes.DodgerBlue : 
             item.BackgroundColor;
e.Graphics.FillRectangle(brush, e.Bounds.X,
                         e.Bounds.Y, e.Bounds.Width, 
                         e.Bounds.Height);

这样,当我将鼠标悬停在项目上时,它会正确地具有不同的颜色,不幸的是,在我单击/选择一个项目并且组合框关闭后,该项目将保留焦点颜色而不是项目颜色,同样适用于 @ 987654325@ 状态和HotLight 甚至似乎都不起作用,因为它从不触发。

我该如何做到这一点,它只会在下拉菜单打开时悬停在项目上时使用焦点颜色,并在选择项目时使用正确的项目颜色?

【问题讨论】:

    标签: c# winforms combobox .net-4.5


    【解决方案1】:

    好的,显然问题不在于平局,而在于控制的焦点。

    我的解决方法是覆盖我的CustomComboBox OnSelectedIndexChanged 事件,如下所示:

    protected override void OnSelectedIndexChanged(EventArgs e)
    {
        base.OnSelectedIndexChanged(e);
        if (Focused)
        {
            Parent.Focus();
        }
    }
    

    并使其将焦点设置到父控件,从而使项目一旦选择就具有其原始颜色。

    如果有适当的解决方案,除了使用父控件设置焦点之外,我很想听听。

    【讨论】:

      猜你喜欢
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多