對於Winforms應用程序,我正在尋找一種能夠顯示文本並支持單獨線條顏色(每行的前景和背景顏色)的控件。Winforms控件顯示文本並支持單獨的線條着色
例如,我想讓第1行顯示綠色背景色,第4行顯示紅色。
對於Winforms應用程序,我正在尋找一種能夠顯示文本並支持單獨線條顏色(每行的前景和背景顏色)的控件。Winforms控件顯示文本並支持單獨的線條着色
例如,我想讓第1行顯示綠色背景色,第4行顯示紅色。
一個ListView控制可能是最容易的事情,你需要什麼(只要它只是用於顯示)。將其View財產設置爲List
。每個項目是ListViewItem,您可以在其中設置foreground和background顏色。
如果你不需要編輯工具,你可以使用ListView控件(在Details模式下)或者TreeControl控件。使用這些控件進行編輯將一次只限制一行(如Windows資源管理器中的重命名工具)。
如果您確實需要編輯工具,那麼您需要基於RichFlexBox的控件,如ChrisF所示。
這聽起來像你可能需要一個富文本編輯器控件。
有大量的第三方控件的約 - 其中一人CodeProject
過去,我爲這種類型的控件使用了自定義組合框。我在構造函數中將DrawMode設置爲OwnerDrawVariable,並重寫OnDrawItem方法。這樣,您可以使用任何顏色或樣式爲組合框中的每個項目繪製背景。
下面的代碼以灰色背景繪製每一個其他項目,如this post中顯示的圖像,但是您可以在OnDrawItem方法中自定義它。這個例子還支持組合框中的多個列和文本包裝,但這只是使事情不必要地複雜化。
Protected Overrides Sub OnDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs)
MyBase.OnDrawItem(e)
//Don't draw the custom area if in DesignMode.
If Me.DesignMode Then Return
//Don't draw the custom area if the index is -1.
If e.Index = -1 Then Return
e.DrawBackground()
Dim boundsRect As Rectangle = e.Bounds
//Shift everything just a bit to the right.
Dim lastRight As Integer = 2
Dim brushForeColor As Color
Dim bckColor As Color
Dim lineColor As Color
If Not (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
//Item is not selected, use _BackColorOdd and _BackColorEven.
If e.Index Mod 2 = 0 Then
bckColor = _BackColorEven
Else
bckColor = _BackColorOdd
End If
//Use black text color.
brushForeColor = Color.Black
//Use dark line color.
lineColor = _BackColorSelected
Else
//Item is selected, use the 'Selected' background color.
bckColor = _BackColorSelected
//Item is selected, use white font color.
brushForeColor = Color.White
//Use white line color.
lineColor = Color.White
End If
//Draw the background rectangle with the appropriate color.
Using brushBackColor As New SolidBrush(bckColor)
e.Graphics.FillRectangle(brushBackColor, e.Bounds)
End Using
Using linePen As New Pen(lineColor)
Using brsh As New SolidBrush(brushForeColor)
//This is the multi-column stuff.
For colIndex As Integer = 0 To _ColumnNames.Count - 1
//Variant(Object) type used to support different data types in each column.
Dim itm As Object
itm = FilterItemOnProperty(Items(e.Index), _ColumnNames(colIndex))
boundsRect.X = lastRight
boundsRect.Width = _ColumnWidths(colIndex)
lastRight = boundsRect.Right
e.Graphics.DrawString(itm, Me.Font, brsh, boundsRect)
//Draw a divider line.
If colIndex < _ColumnNames.Count - 1 Then
e.Graphics.DrawLine(linePen, boundsRect.Right, boundsRect.Top, _
boundsRect.Right, boundsRect.Bottom)
End If
Next
End Using
End Using
End Sub
這可能有點矯枉過正,但它會起到一定的作用。