【发布时间】:2009-12-07 22:44:11
【问题描述】:
对于 Winforms 应用程序,我正在寻找能够显示文本并支持单独的线条颜色(每行的前景色和背景色)的控件。
例如,我希望第 1 行背景颜色为绿色,第 4 行背景颜色为红色。
【问题讨论】:
标签: c# winforms controls formatting
对于 Winforms 应用程序,我正在寻找能够显示文本并支持单独的线条颜色(每行的前景色和背景色)的控件。
例如,我希望第 1 行背景颜色为绿色,第 4 行背景颜色为红色。
【问题讨论】:
标签: c# winforms controls formatting
ListView 控件可能是您需要的最简单的东西(只要它只是用于显示)。将其View 属性设置为List。每个项目都是一个ListViewItem,您可以在其上设置foreground和background颜色。
【讨论】:
过去,我曾为此类控件使用自定义组合框。我在构造函数中将 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
这对于您想要的东西来说可能有点矫枉过正,但它会解决问题。
【讨论】:
如果您不需要编辑工具,您可以使用 ListView 控件(在详细信息模式下)或 TreeControl。使用这些控件进行编辑将被限制为一次一行(如 Windows 资源管理器中的重命名工具)。
如果您确实需要编辑工具,那么您将需要一个基于 RichTextBox 的控件,正如 ChrisF 所建议的那样。
【讨论】:
听起来您可能需要一个富文本编辑器控件。
有很多 3rd 方控件 - 包括 CodeProject 上的一个
【讨论】: