【问题标题】:Customizing the appearance of a Windows Forms combo box自定义 Windows 窗体组合框的外观
【发布时间】:2011-02-01 14:31:04
【问题描述】:

这是我的工作:

Public Class ComboBox
    Inherits System.Windows.Forms.ComboBox

    Public Sub New()
        SetStyle(ControlStyles.OptimizedDoubleBuffer _
        Or ControlStyles.UserPaint, True)
    End Sub

    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        e.Graphics.FillRectangle(gradient, ClientRectangle)
        // The preceding line is a simplification of about 50 lines of code.

        If Not String.IsNullOrEmpty(Text) Then
            Dim rect As New Rectangle(2, 0, Width - 2, Height)

            Using format As New StringFormat()
                format.LineAlignment = StringAlignment.Center

                Using brush As New SolidBrush(ForeColor)
                    e.Graphics.DrawString(Text, Font, brush, rect, format)
                End Using
            End Using
        End If

        e.Graphics.FillPolygon(Brushes.Black, New Point() { _
        New Point(Width - 5, Height \ 2 - 1), _
        New Point(Width - 12, Height \ 2 - 1), _
        New Point(Width - 9, Height \ 2 + 3)})
    End Sub
End Class

我有两个问题:

  1. 它的高度始终为 24。
  2. 下拉列表使用难看的 Windows 3.1 字体呈现。

【问题讨论】:

  • 你想做什么?为什么不能使用常规的 ComboBox?
  • 公司聘请了一位艺术家。他画东西。现在我必须实施它。 (在你问之前:我不能使用 WPF。)

标签: .net winforms combobox custom-controls


【解决方案1】:

要解决字体问题,请在 OnControlCreated 中设置 UserPaint 样式而不是构造函数,如下所示:

    protected override void OnCreateControl()
    {
        base.OnCreateControl();
        SetStyle(ControlStyles.UserPaint, true);
    }

【讨论】:

    【解决方案2】:

    您的问题显然出在“Full of Code”部分。我建议你一次解决一个问题:

    1) 高度问题:可能是您将高度设置为 24,如果您更改高度,控件会相应地调整大小?你看过 Control.PreferredSize 属性吗?看这里:http://msdn.microsoft.com/en-us/library/system.windows.forms.control.preferredsize.aspx

    2) 字体问题。如果不查看代码,这是无法诊断的。我只能说确保您使用您想要使用的任何字体正确绘制下拉元素。

    【讨论】:

    • 1) 我试过改变高度 - 改变被忽略了。 PreferredSize 是只读的。 2)我已经修改了代码。我没有绘制下拉元素。它们是由一些我无法影响的 Windows API 代码绘制的。
    【解决方案3】:

    高度问题几乎是肯定的,因为您从 ComboBox 继承,然后使用标准 API 调用来绘制大部分内容,并且当 Windows 绘制组合框时,高度由字体大小和对 Height 属性的任何更改固定被忽略。

    同样,Windows 使用默认字体,因为您没有在 API 调用中更改或设置它。

    在继承和进行细微修改时,组合框并不十分友好。您可能必须完全提供您自己的自定义实现,这也不是微不足道的。您可能无法找到 3rd 方自定义控件来呈现您想要的内容。贵公司在没有实际考虑可用控件等的情况下进行艺术家演绎时犯了一个错误。抱歉...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      相关资源
      最近更新 更多