【问题标题】:One word bold inside a text in winform controlwinform控件中文本内的一个单词加粗
【发布时间】:2011-01-17 19:54:36
【问题描述】:

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

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”,或者没有达到断点的正方形......

【问题讨论】:

  • 您需要将 Listbox 的 DrawMode 属性设置为 OwnerDrawn。请检查我的答案

标签: c# .net winforms formatting listbox


【解决方案1】:

我认为您可以从 VS 2008 开始使用 HTML 标记,例如<b>01</b> car 用于 01 汽车,用于一些文本。我必须检查这是否适用于列表框。

【讨论】:

    【解决方案2】:

    有可能,您需要使用列表框的 DrawItem 事件,然后您可以根据需要绘制项目:

    MSDN 上的DrawItem event

    这是一个用不同颜色绘制每个项目的示例:

    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 属性才能触发事件:

    此事件由所有者绘制的 ListBox 使用。该事件仅在 DrawMode 属性设置为 DrawMode.OwnerDrawFixed 或 DrawMode.OwnerDrawVariable 时引发。您可以使用此事件来执行在 ListBox 中绘制项目所需的任务。

    【讨论】:

    • 这样有效吗? (谈论资源消耗和处理使用)任何功能损失?比如选择、复制、能够将字符串收集回来或其他什么?
    • 我认为它是有效的,当然有可能把它搞砸,例如,如果你以某种方式触发了这段代码的重绘,那么它会开始闪烁,或者你在这个函数中做一些计算密集型的事情
    • 据我了解,此事件仅用于重绘单个项目,因此它只会针对可见项目运行。这又是非常好的和高效的,你不必从你的代码中处理这个问题。
    • 我已经做到了,可以肯定的是,在事件选项卡中单击“drawicon”文本框创建了事件,然后编写了代码,但它似乎使用了一个旧的,里面有一个断点它没有达到..我还需要做什么才能将此功能分配给列表框?
    • 你能把你的代码发给我吗?或张贴在这里?我需要查看并调试它
    猜你喜欢
    • 1970-01-01
    • 2015-04-03
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    相关资源
    最近更新 更多