How do I change the color of a word inside a listbox

只愿长相守 提交于 2019-12-02 06:37:34

There is no standard way of doing it in Windows Forms. You'd have to render the list items manually (create an owner drawn list box). In WPF this would be an easy task.

EDIT
Drawing only part of a string in a different font is not an easy task. What I'd try is the following:

Introduce tokens that tell you "bold start" and "bold end" - a bit like in HTML. Let's call them the same as in HTML. So your string could look like this:

Hello, I am <b>bold</b> text<b>!</b>

Now I'd tokenize my string into text that is non-bold and text that is bold. I'd get the following parts:

Hello, I am
bold
text
!

Now I'd draw each part using the following algorithm:

  1. Draw string in current format at current position x
  2. increase position x by width of the string drawn in step 1
  3. change formatting according to upcoming string
  4. goto 1

In step 2 the Graphics.MeasureString method would be called to get the width of the string.

Doing this for the 4 sample parts above would result in:

Hello, I am
Hello, I am bold
Hello, I am bold text
Hello, I am bold text !

A simple TextBox can have its Foreground property set, but it applies to the entire text within the TextBox.

If you want specific words to be "highlighted", you either need to split the sentence in several TextBoxes (dirty), or make use of a RichTextBox

Youenn Bouglouan

Giannosfor, in response to your comment, you'll have to use the parameter e of the event handler to choose which item you want to hightlight (link here).

Look at the response from Shadow Wizard and particularly at the use of e.Index.

Graphics g = e.Graphics;
...
g.FillRectangle(new SolidBrush(color), e.Bounds);

Variable g represent the graphic part of your current item e. Method FillRectangle allows you to change the color of the item's background.

Edit 1:

I tried to do as you say in the comment below but it seems there is no way to hightlight only a part of a string using ListBox. To me it seems the only control that is able to support that is the RichTextBox. A solution might be to implement your own user control in the form of a list of RichTextBoxes.

Building on @Thorsten Dittmar answer, I developed pretty much exactly what you are looking for in a single ListBox. You can find it at https://advancedlistbox.codeplex.com/.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!