本文介绍了Listbox 手动 DrawItem 大字号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以红色绘制以 * 字符结尾的项目(并删除该 * 字符)并以黑色绘制其他项目.

I'm trying to draw items that end of them is an * character in red (and remove that * character) and draw other items in black color.

这是我的代码:

    private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        e.DrawBackground() ; //Draw our regular background
        if (Microsoft.VisualBasic.Strings.Right(listBox1.Items[e.Index].ToString(), 1) == "*")
        {
            e.Graphics.DrawString(Microsoft.VisualBasic.Strings.Mid(listBox1.Items[e.Index].ToString(),1,listBox1.Items[e.Index].ToString().Length - 1), e.Font, Brushes.Red, e.Bounds);    //Draw the item text in red!
        }
        else
        {
            e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds); //Draw the item text in its regular color
        }
    }

还将列表框的 DrawMode 属性设置为 OwnerDrawVariable.

Also DrawMode property of the listbox is set to OwnerDrawVariable.

当列表框的字体为默认字体时,我的代码工作正常.

My code is working fine when the font of listbox is the default font.

但是当我将字体大小从 8.25(默认大小)更改为 14 时,一半的文本绘制在列表框上.像这样:

But When I change the font size from 8.25 (default size) to 14, half of the text draws on the listbox. like this:

但是使用默认字体大小,一切都是正确的.

But with default font size, everything is correct.

有什么问题?

推荐答案

你必须处理 MeasureItem 事件并在那里设置项目的高度:

You have to handle the MeasureItem event and set the height of the items there:

private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
     e.ItemHeight = listBox1.Font.Height;
}

这篇关于Listbox 手动 DrawItem 大字号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 08:04