gpt4 book ai didi

c# - 覆盖 ListBox 的 DrawItem - 未选择的项目不会重绘

转载 作者:太空狗 更新时间:2023-10-30 00:28:21 25 4
gpt4 key购买 nike

这是一个 C# 桌面应用程序。我的 ListBoxDrawStyle 属性设置为 OwnerDrawFixed

问题:我重写了 DrawItem 以用不同的字体绘制文本,它起作用了。但是,当我在运行时开始调整表单大小时,所选项目已正确绘制,但其余部分未重新绘制,导致未选定项目的文本看起来损坏。

这是我的代码:

private void listDevices_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();

string textDevice = ((ListBox)sender).Items[e.Index].ToString();

e.Graphics.DrawString(textDevice,
new Font("Ariel", 15, FontStyle.Bold), new SolidBrush(Color.Black),
e.Bounds, StringFormat.GenericDefault);


// Figure out where to draw IP
StringFormat copy = new StringFormat(
StringFormatFlags.NoWrap |
StringFormatFlags.MeasureTrailingSpaces
);
copy.SetMeasurableCharacterRanges(new CharacterRange[] {new CharacterRange(0, textDevice.Length)});

Region[] regions = e.Graphics.MeasureCharacterRanges(
textDevice, new Font("Ariel", 15, FontStyle.Bold), e.Bounds, copy);

int width = (int)(regions[0].GetBounds(e.Graphics).Width);
Rectangle rect = e.Bounds;
rect.X += width;
rect.Width -= width;

// draw IP
e.Graphics.DrawString(" 255.255.255.255",
new Font("Courier New", 10), new SolidBrush(Color.DarkBlue),
rect, copy);

e.DrawFocusRectangle();
}

listDevices.Items.Add("Device001");
listDevices.Items.Add("Device002");

此外,正确绘制的项目(选定的项目)在调整表单大小时闪烁。没什么大不了的,但如果有人知道为什么...... tnx

最佳答案

将以下代码放入调整大小事件中:

private void listDevices_Resize(object sender, EventArgs e) {
listDevices.Invalidate();
}

这应该会导致重绘所有内容。

要停止闪烁,您需要双缓冲。

为此,创建一个派生自 ListBox 的新类,并将以下内容放入构造函数中:

this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

或者只是将其粘贴到代码文件中:

using System.Windows.Forms;

namespace Whatever {
public class DBListBox : ListBox {
public DBListBox(): base() {
this.DoubleBuffered = true;
// OR
// this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}
}
}

将“Whatever”替换为您的项目使用的 namespace ,或使其更有用。编译后,您应该能够在表单设计器中添加一个 DBListBox。

关于c# - 覆盖 ListBox 的 DrawItem - 未选择的项目不会重绘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3274861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com