在Visual c#Express Edition中,是否可以在ListBox中创建一些(但不是全部)项目?我在API中找不到任何类型的选项。
答案 0 :(得分:30)
您需要将列表框的DrawMode更改为DrawMode.OwnerDrawFixed。查看msdn上的这些文章:
DrawMode Enumeration
ListBox.DrawItem Event
Graphics.DrawString Method
另请在msdn论坛上查看这个问题:
Question on ListBox items
一个简单的例子(两个项目 - Black-Arial-10-Bold):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ListBox1.Items.AddRange(new Object[] { "First Item", "Second Item"});
ListBox1.DrawMode = DrawMode.OwnerDrawFixed;
}
private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), new Font("Arial", 10, FontStyle.Bold), Brushes.Black, e.Bounds);
e.DrawFocusRectangle();
}
}
答案 1 :(得分:1)
要添加到MindaugasMozūras的解决方案,我遇到了一个问题,我的e.Bounds
不够大,文字被切断了。要解决此问题(感谢帖子here),您可以覆盖OnMeasureItem
事件并将DrawMode更改为DrawMode.OwnerDrawVariable
。
在设计师:
listBox.DrawMode = DrawMode.OwnerDrawVariable;
在处理程序中:
void listBox_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = 18;
}
解决了高度切断文字的问题。
答案 2 :(得分:0)
以下是展示相同内容的代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (FontFamily fam in FontFamily.Families)
{
listBox1.Items.Add(fam.Name);
}
listBox1.DrawMode = DrawMode.OwnerDrawFixed; // 属性里设置
}
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), new Font(listBox1.Items[e.Index].ToString(), listBox1.Font.Size), Brushes.Black, e.Bounds);
//e.DrawFocusRectangle();
}
}
}
答案 3 :(得分:0)
一个更通用的例子,它使用发送者,并且实际上尊重前景色(例如,如果选择了项目,或者用户使用了另一种颜色集,其中黑色前景色实际上不可读)和当前ListBox字体:< / p>
private void listBoxDrawItem (object sender, DrawItemEventArgs e)
{
Font f = e.Font;
if (e.Index == 1) //TODO: Your condition to make text bold
f = new Font(e.Font, FontStyle.Bold);
e.DrawBackground();
e.Graphics.DrawString(((ListBox)(sender)).Items[e.Index].ToString(), f, new SolidBrush(e.ForeColor), e.Bounds);
e.DrawFocusRectangle();
}
您需要将DrawMode设置为OwnerDrawFixed(例如,在设计器中)。
答案 4 :(得分:0)
使所选项目变为粗体
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ListBox1.Items.AddRange(new Object[] { "me", "myself", "bob"});
// set the draw mode to fixed
ListBox1.DrawMode = DrawMode.OwnerDrawFixed;
}
private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
{
// draw the background
e.DrawBackground();
// get the font
Font font = new Font(e.Font, (e.State & DrawItemState.Selected) == DrawItemState.Selected ? FontStyle.Bold : FontStyle.Regular);
// draw the text
e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), font, new SolidBrush(ListBox1.ForeColor), e.Bounds);
e.DrawFocusRectangle();
}
}