How to make part of ListViewItem text to be bold?

给你一囗甜甜゛ 提交于 2019-12-11 05:58:56

问题


I have a ListView in Details mode, and I'd like to have some of its items' text in bold (for highlighting where it finds some substring in the item text).

So something like this:

Somefilename/boldText/etc

Is there any way to do that?


回答1:


Okay, so this is going to be difficult because you're going to have to OwnerDraw your ListView first by setting that property to true. Now that you've done that you're going to need to implement DrawColumnHeader and place this line in it:

e.DrawDefault = true;

Next you'll need to implement the following code, either in DrawItem or DrawSubItem depending on which area it exists in. Keep in mind the code I'm giving you isn't fully complete because it's not parsing the string or anything and further you still need to implement drawing a selected item now because your drawing the text on your own.

var boldFont = new Font(this.Font, FontStyle.Bold);
var location = new PointF(e.Bounds.Location.X, e.Bounds.Location.Y);

e.Graphics.DrawString("Somefilename/", this.Font, Brushes.Black, location);
var size = e.Graphics.MeasureString("Somefilename/", this.Font);

location.X += size.Width;
e.Graphics.DrawString("boldText", boldFont, Brushes.Black, location);
size = e.Graphics.MeasureString("boldText", boldFont);

location.X += size.Width;
e.Graphics.DrawString("/etc", this.Font, Brushes.Black, location);

Another thing to note is that you'll have to play with the offsets a little because some fonts have margins and bolded fonts take up more room.

If the Item is not a SubItem then just implement the e.DrawDefault = true; for the DrawSubItem event - and vica versa if the item is a SubItem then implement that line for DrawItem.




回答2:


You'll have to override OnPaint. Try these links:

Make portion of a Label's Text to be styled bold

Custom ListView in Winforms?

But, the listview is not painted by the .net framework and is only supported. So, even if you override the OnPaint, it might not be called. So you might have to override your listview control as well.



来源:https://stackoverflow.com/questions/12090727/how-to-make-part-of-listviewitem-text-to-be-bold

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