c# - winform控件中文本中的一个粗体字

标签 c# .net winforms formatting listbox

我想要一些方法来使给定的单词变粗(列表框中每个项目的前两个字符),而不是别的,像这样:

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/

相关文章:

c# - SPA 的 Asp.net 核心 Web API - 如何实现 Swagger 身份验证而无需在 Web API 外部获取访问 token 并传递它?

c# - 将非托管 dll 的 Delphi 代码转换为 C#

c# - ViewModel在页面上为Null

c# - WinForm c# : Check first run and show message

C# GUI 可编辑 DataGridView

c# - 像 ajax 标记完成一样工作的 Winforms 控件

c# - WPF 和 Prism View 叠加

c# - securestring 如何编码为非托管代码?

c# - 使用 GraphicsPath 正确绘制文本

c# - DataGridView 只读 "bug"