我想要一些方法来使给定的单词变粗(列表框中每个项目的前两个字符),而不是别的,像这样:
01车
02房子
03市场
至于这三个,作为列表框控件中的项目,总是前两个字符,其余的不应该是粗体。
有什么实用的方法吗?
数据:
- Visual Studio 2008
- .NET 3.5
要求:
private void lstMaster_DrawItem(object sender, DrawItemEventArgs e)
{
//TEST
e.DrawBackground();
Brush myBrush = Brushes.Black;
Pen pen = new Pen(myBrush);
e.Graphics.DrawRectangle(pen, 0, 0, 10, 10); //BREAKPOINT HERE
e.Graphics.DrawString("aaa" + lstMaster.Items[e.Index].ToString(),
e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
它只是保持不变,没有矩形,没有“AAA”,或者没有达到断点的方形......
最佳答案
有可能,您需要使用列表框的 DrawItem 事件,然后您可以从那里绘制您想要的项目:
DrawItem event在 MSDN 上
这是一个用不同颜色绘制每个项目的示例:
private void ListBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
// Draw the background of the ListBox control for each item.
e.DrawBackground();
// Define the default color of the brush as black.
Brush myBrush = Brushes.Black;
// Determine the color of the brush to draw each item based
// on the index of the item to draw.
switch (e.Index)
{
case 0:
myBrush = Brushes.Red;
break;
case 1:
myBrush = Brushes.Orange;
break;
case 2:
myBrush = Brushes.Purple;
break;
}
// Draw the current item text based on the current Font
// and the custom brush settings.
e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(),
e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
// If the ListBox has focus, draw a focus rectangle around the selected item.
e.DrawFocusRectangle();
}
根据文档,您还需要更改 DrawMode列表框的属性以便触发事件:
This event is used by an owner-drawn ListBox. The event is only raised when the DrawMode property is set to DrawMode.OwnerDrawFixed or DrawMode.OwnerDrawVariable. You can use this event to perform the tasks needed to draw items in the ListBox.
关于c# - winform控件中文本中的一个粗体字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2280327/