【问题标题】:Emulate System style on custom .NET Combobox在自定义 .NET 组合框上模拟系统样式
【发布时间】:2018-11-29 14:19:45
【问题描述】:

我已经派生了 ComboBox 类,以便对列表项进行自定义布局。这是一个 DropDown 列表样式的 Combobox,外观漂亮,而​​自定义的则看起来像老式的。

是否有任何方法可以模拟或强制控件绘制“windows 默认样式”布局,同时仍具有自定义设计?也就是说,具有与上图右侧类似的样式,带有渐变背景(或其他任何内容,具体取决于 windows 的版本)。

这是我到目前为止所做的:

    public ComboBoxRGB()
    {
        this.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
        this.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
    }

    protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs e)
    {
        base.OnDrawItem(e);

        if (Items.Count > 0)
        {
            if (e.Index > -1)
            {
                if (Items[e.Index] == null) return;

                int BarWidth = 16;
                int BarSpacing = 1;
                int Spacing_Top = 2;
                int Spacing_Left = 3;
                int Spacing_Right = 4;

                ComboBoxRGBItem item;
                try
                {
                    item = (ComboBoxRGBItem)Items[e.Index];
                }
                catch { return; }

                e.DrawBackground();
                e.DrawFocusRectangle();

                //Draw color indicator
                System.Drawing.SolidBrush bColor = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(item.Red, item.Green, item.Blue));
                e.Graphics.FillRectangle(bColor, Spacing_Left + e.Bounds.Left, e.Bounds.Top + Spacing_Top, 12, 12);

                //Draw text
                System.Drawing.SolidBrush sbText = (e.State == System.Windows.Forms.DrawItemState.Selected) ? new System.Drawing.SolidBrush(System.Drawing.Color.White) : new System.Drawing.SolidBrush(System.Drawing.Color.Black);
                e.Graphics.DrawString(item.Text, e.Font, sbText, Spacing_Left + e.Bounds.Left + BarWidth + Spacing_Right, e.Bounds.Top);

            } //IF_Index
        } //IF_Items_Count
    }

如果有人知道如何做到这一点,我将非常高兴。我想尝试手动模拟外观,因为这会随着 Windows 版本的变化而变化。

【问题讨论】:

    标签: c# winforms custom-controls


    【解决方案1】:

    我无法在互联网上找到有关此的信息,所以我想不可能使用 system-default-style 自动绘制背景。

    目前使用的解决方案是完全手动绘制,通过重写Paint方法,但这需要考虑到正在执行的Windows版本,并使用不同的设计来绘制控件。

    如果有人有不同的解决方案或任何建议,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-12
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多