简体   繁体   English

如何使ListViewItem文本的一部分变为粗体?

[英]How to make part of ListViewItem text to be bold?

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). 我在“详细信息”模式下有一个ListView,我想将其某些项目的文本加粗(突出显示在项目文本中找到子字符串的位置)。

So something like this: 所以像这样:

Somefilename/ boldText /etc Somefilename / boldText / etc

Is there any way to do that? 有什么办法吗?

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 . 好的,这将很困难,因为您必须首先通过将该属性设置为trueOwnerDraw ListView Now that you've done that you're going to need to implement DrawColumnHeader and place this line in it: 现在,您已经需要实现DrawColumnHeader并将此行放入其中:

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. 接下来,您需要根据DrawSubItem在的区域在DrawItemDrawSubItem实现以下代码。 请记住,我提供给您的代码并不完整,因为它没有解析字符串或任何东西,因此您现在仍然需要实现绘制所选项目的功能,因为您可以自己绘制文本。

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; 如果Item不是SubItem则只需实现e.DrawDefault = true; for the DrawSubItem event - and vica versa if the item is a SubItem then implement that line for DrawItem . 对于DrawSubItem事件-反之亦然,如果该项是SubItem ,则为DrawItem实现该行。

You'll have to override OnPaint. 您必须重写OnPaint。 Try these links: 试试这些链接:

Make portion of a Label's Text to be styled bold 将标签文本的一部分设置为粗体

Custom ListView in Winforms? 在Winforms中自定义ListView?

But, the listview is not painted by the .net framework and is only supported. 但是,.net框架不会绘制listview,仅支持它。 So, even if you override the OnPaint, it might not be called. 因此,即使您覆盖OnPaint,也可能不会调用它。 So you might have to override your listview control as well. 因此,您可能还必须重写listview控件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM