当我增加列表框中的字体大小时,较大的文本字符串会被垂直剪切,因为该项目的绘制矩形大小(间距)不会随字体大小而增加。文本的每下一行都覆盖前一行,因此只有字母的顶部显示较大的字体。
如果我不更改字体大小,一切都可以与DrawMode.OwnerDrawFixed
一起正常工作。小于正常的字体可以正确显示。只有较大的字体会被剪切。我更改为DrawMode.OwnerDrawVariable
,并添加了MeasureItem事件处理程序以显式测量较大的字体大小,但这也不起作用。
我想念什么?谢谢。
更新:我根据@Jimi在他的评论中提供的链接中的示例在下面提供了工作代码。我错过了MeasureItem事件仅运行一次(或在必要时)而不是针对每个绘制项目运行的想法。因此,当您在列表框中更改字体大小时,必须手动触发新的MeasureItem事件。生成事件的诀窍是将DrawMode.OwnerDrawVariable
翻转为“正常”并返回。
listBox1.DrawMode = DrawMode.OwnerDrawVariable;
listBox1.DrawItem += DrawItemHandler;
listBox1.MeasureItem += MeasureItemHandler;
private void MeasureItemHandler(object sender, MeasureItemEventArgs e) {
// must measure the height to allow for user font size changes
var listBox = (ListBox) sender;
e.ItemHeight = listBox.Font.Height;
}
public void DrawItemHandler(object sender, DrawItemEventArgs e) {
// prepare text and colors for drawing here
//
using (var bgbrush = new SolidBrush(bgcolor)) {
using (var fgbrush = new SolidBrush(fgcolor)) {
e.Graphics.FillRectangle(bgbrush, e.Bounds);
e.Graphics.DrawString(logEntry.EntryText, e.Font, fgbrush, e.Bounds);
}
}
e.DrawFocusRectangle();
}
private void fontUpToolStripMenuItem_Click(object sender, EventArgs e) {
// To increase size alone, use the original font family
var size = listBox1.Font.Size;
if (size < 32) {
// set the new font size, register it with the list box, and then
// flip the draw mode back and forth to trigger a MeasureItem event.
// The measure event will recalculate the bounds for all items in the box.
listBox1.Font = new Font(listBox1.Font.FontFamily, size + 1);
listBox1.Height = listBox1.Font.Height;
listBox1.DrawMode = DrawMode.Normal;
listBox1.DrawMode = DrawMode.OwnerDrawVariable;
listBox1.Invalidate();
}
}