问题描述
在属性 DrawMode
设置为 OwnerDrawVariable
的 Windows.Forms.ListBox
中,ListBox
似乎缓存物品的高度,有什么好处.
In a Windows.Forms.ListBox
with the property DrawMode
set to OwnerDrawVariable
, the ListBox
seems to cache the height of the items, what is good.
BUT,是依赖于宽度的item高度,因为它使用Graphics.MeasureString
来做自动换行,如果ListBox的大小需要计算item的高度代码>已更改.那么问题来了.
BUT, being the item height dependent of the width, because it uses Graphics.MeasureString
to do word wrap, needs to calculate the height of items if the size of the ListBox
has changed. Then there's a problem.
ListBox
默认不这样做,我找不到清除缓存的方法,强制ListBox
引发itemheight事件.
The ListBox
doesn't do this by default, and I can't find a method to clear the cache, forcing the ListBox
to raise the itemheight event.
有什么解决办法吗?我试图获取 ListBox 的源代码,但没有找到任何相关信息来创建派生类并清除此缓存.
Any solution? I tried to get the source for the ListBox but don't find anything about that to make a derived class and clear this cache.
(尝试将项目复制到数组中,清除 ListBox.Items
,然后再次添加数组.这甚至会在 ListBox
调用 drawitem 或项目索引无效的项目高度事件)
(Tried copying the items to an array, clearing the ListBox.Items
, and tem adding the array again. This even throw exceptions as the ListBox
calling the drawitem or itemheight events with invalid item index)
推荐答案
根据这个 MSDN
LB_SETITEMHEIGHT 消息
设置列表框中项目的高度(以像素为单位).如果列表框有LBS_OWNERDRAWVARIABLE 样式,此消息设置项目的高度由 wParam 参数指定.否则,此消息设置高度列表框中的所有项目.
Sets the height, in pixels, of items in a list box. If the list box has the LBS_OWNERDRAWVARIABLE style, this message sets the height of the item specified by the wParam parameter. Otherwise, this message sets the height of all items in the list box.
这样就可以了
private const int LB_SETITEMHEIGHT = 0x01A0;
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
private void ListBoxExample_Resize(object sender, EventArgs e)
{
for (int i = 0; i < ListBoxExample.Items.Count; i++)
{
MeasureItemEventArgs eArgs = new MeasureItemEventArgs(null, i);
ListBoxExample_MeasureItem((object)ListBoxExample, eArgs);
SendMessage((IntPtr) ListBoxExample.Handle, LB_SETITEMHEIGHT, (IntPtr) i, (IntPtr) e.ItemHeight);
}
}
MeasureItemEventArgs
接受 Graphics
对象,如有必要,从控件创建一个对象并将其传递到第一个参数中.
The MeasureItemEventArgs
accepts a Graphics
object, if necessary, create one from the control and pass it in the first argument.
这篇关于Windows.Forms.ListBox 与 OwnerDrawVariable 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!