繁体   English   中英

具有自动调整大小的列表框,水平滚动条

[英]Listbox with auto-sizing, horizontal scroll bar

我试图使用以下代码在列表框中找到最长项目的宽度,然后更改列表框的HorizontalExtent属性以使其适合水平滚动条范围内的项目:

Graphics widthFinder = listBox_Transactions.CreateGraphics();
int needScrollWidth = 0; int checkVal = 0;
for (int i = 0; i < listBox_Transactions.Items.Count; i++)
{
    checkVal = (int)widthFinder.MeasureString(listBox_Transactions.Items[i].ToString(), listBox_Transactions.Font).Width + 1;
    if (needScrollWidth < checkVal)
    { needScrollWidth = checkVal; }
}

listBox_Transactions.HorizontalScrollbar = true;
listBox_Transactions.HorizontalExtent = needScrollWidth;
listBox_Transactions.Invalidate();

该代码似乎按预期方式工作,但widthFinder.MeasureString(listBox_Transactions.Items[i].ToString(), listBox_Transactions.Font).Width始终返回164。我已经搜索了可能发生这种情况的原因,但没有找到没找到。 有任何想法吗?

很难确定,可悲的是,在我撰写本文时,我没有要求澄清作为评论的声誉,但是...

我已经尝试过您的代码,并且对我来说效果很好。 我所能想到的就是,如果您使用其他DisplayMember和ValueMember,那么我假设您是将对象添加到Items属性中,而不是简单类型。 在这种情况下

listBox_Transactions.Items[i].ToString()

最终将为您提供对象的名称,而不是您想要的值。

假设我有一个Foo类的列表,并将其添加到您的列表框中

List<Foo> fooList = new List<Foo>();
fooList.Add(new Foo() { Bar = 1 });
fooList.Add(new Foo() { Bar = 2 });
fooList.Add(new Foo() { Bar = 3 });
fooList.Add(new Foo() { Bar = 45 });

listBox_Transactions.Items.AddRange(fooList.ToArray());
listBox_Transactions.DisplayMember = "Bar";
listBox_Transactions.ValueMember = "Bar";

然后在我的代码中

listBox_Transactions.Items[i].ToString()

我会得到价值

"Namespace.Foo"

而不是我想要获得的价值。 因此,这将总是导致给出相同的字符串长度。

要解决此问题,请在上述代码中像这样将其转换回您的对象类型:

((Foo)listBox_Transactions.Items[i]).Bar.ToString()

希望这会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM