の派生クラスがあり、ドロップダウンリストアイテムをカスタム描画するためにComboBox
オーバーライドします。OnDrawItem
コンボボックスの編集部分(ドロップダウンが閉じているときに表示される部分、またはドロップダウンが開いているときに上部に表示される部分)を、デフォルトがComboBox
機能する方法で描画し続けるにはどうすればよいですか?基本機能を呼び出してComboBox
編集領域部分を描画する方法はありますか、それともOwnerDrawモードでは使用できませんか?DropDown
使用できない場合、とDropDownList
スタイルの両方の編集領域部分の外観をシミュレートするにはどうすればよいですか?
2 に答える
DrawItemEventArgs
合格したものは、e
操作するためのいくつかのツールを提供します。OwnerDraw
システムがモードで描画するようなものを複製するには、次のようにします。
Public Class MyComboBox
Inherits System.Windows.Forms.ComboBox
Private _font As Font = New Font(FontFamily.GenericSansSerif, 9.0, _
FontStyle.Regular)
Protected Overrides Sub OnDrawItem(e As DrawItemEventArgs)
e.DrawBackground()
If e.Index = -1 Then Exit Sub
e.Graphics.DrawString(Me.Items(e.Index).ToString, _font, _
System.Drawing.Brushes.Black, _
New RectangleF(e.Bounds.X, e.Bounds.Y, _
e.Bounds.Width, e.Bounds.Height))
e.DrawFocusRectangle()
End Sub
End Class
編集 :
表示されたアイテムとドロップダウン領域に描画されたアイテムの描画動作を変更する場合は、DroppedDown
プロパティに基づいて描画コードを分岐できます。
e.DrawBackground()
If e.Index = -1 Then Exit Sub
If Not Me.DroppedDown Then
e.Graphics.DrawString(Me.Items(e.Index).ToString, _font,
System.Drawing.Brushes.Black, _
New RectangleF(e.Bounds.X, e.Bounds.Y, _
e.Bounds.Width, e.Bounds.Height))
Else
' do whatever you want - draw something else
Dim rectangle As Rectangle = New Rectangle(2, e.Bounds.Top + 2, _
e.Bounds.Height, e.Bounds.Height - 4)
e.Graphics.FillRectangle(Brushes.Blue, rectangle)
e.Graphics.DrawString("foo...I'm item #" & e.Index, _font, _
System.Drawing.Brushes.Black, _
New RectangleF(e.Bounds.X + rectangle.Width, _
e.Bounds.Y, e.Bounds.Width, e.Bounds.Height))
End If
e.DrawFocusRectangle()
同様に、などに基づいて分岐することができますIf Me.DropDownStyle = ComboBoxStyle.DropDownList ...
。各ケースを好きなように処理します。OSで描画されるコンポーネントによって提供されるグラデーション、テーマ要素、またはその他の機能が必要な場合は、それらを自分で描画する必要があります。
この質問は実際には2つの問題をカバーしています。
コンボボックスの編集領域に表示されるデータをターゲットにするには、OnDrawItemイベントのイベント引数のStateプロパティを次のように使用します。
Protected Overrides Sub OnDrawItem(e As DrawItemEventArgs) ' Draw the background of the item. e.DrawBackground() ' Skip doing anything else if the item doesn't exist. If e.Index = -1 Then Exit Sub If (e.State And DrawItemState.ComboBoxEdit) = DrawItemState.ComboBoxEdit Then ' Draw the contents of the edit area of the combo box. Else ' Draw the contents of an item in the drop down list. ' Draw the focus rectangle. e.DrawFocusRectangle() End If End Sub
OwnerDrawモードでは、ボタンの面にドロップダウン矢印を表示したり、DropDownListスタイルの場合に編集領域をボタンの面に変更したりするなど、システムが使用している視覚的なスタイルのテーマは適用されません。 OnPaintイベントハンドラーを渡します。 この質問は、コンボボックスのビジュアルスタイルを使用するための.NET Framework内にすぐに使用できるメソッド呼び出しがないことを意味しますが、回避策がある場合があります。または、スタイルの実装を手動でプログラムできます。