如何更改列表框所选项目的字体颜色C# [英] How to change font color of listbox selected items C#

查看:105
本文介绍了如何更改列表框所选项目的字体颜色C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改列表框所选项目的字体颜色C#按钮点击



我尝试过:



for(int i = 0; i< lbProductsToBuy.Items.Count; i ++)

{

lbProductsToBuy.SetSelected(i ,true);

i.fontcolor = color.Red;

}

但它不起作用

how to change font color of listbox selected items C# on button click

What I have tried:

for (int i = 0; i < lbProductsToBuy.Items.Count; i++)
{
lbProductsToBuy.SetSelected(i, true);
i.fontcolor = color.Red;
}
but it's not working

推荐答案

您正在尝试更改int的颜色而不是列表框项。



使用ListBox的所有者绘制模式。在设计模式下选择ListBox,并将DrawMode属性更改为OwnerDrawFixed。现在将一个处理程序附加到DrawItem事件,然后使用Graphics类的方法以您喜欢的任何颜色或字体绘制字符串。您需要在DrawItem中执行的操作示例如下:

You are trying to change the colour of an int I not the listbox item.

Use owner-draw mode of the ListBox. Select your ListBox in design-mode and change DrawMode property to OwnerDrawFixed. Now attach a handler to DrawItem event and then use Graphics class's methods to draw your string in any color or font you like. An example of what you need to do in DrawItem would be:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)

   MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem
    if (item != null) 
    {
        e.Graphics.DrawString( // Draw the appropriate text in the ListBox
            item.Message, // The message linked to the item
            listBox1.Font, // Take the font from the listbox
            new SolidBrush(item.ItemColor), // Set the color 
            0, // X pixel coordinate
            e.Index * listBox1.ItemHeight // Y pixel coordinate.  Multiply the index by the ItemHeight defined in the listbox.
        );
    }


这篇关于如何更改列表框所选项目的字体颜色C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆