1

次のコードを使用してリストボックス内の最長のアイテムの幅を見つけ、リストボックスの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();

コードは、常に164を返すことを除いて、期待どおりに機能しているようです。これが発生widthFinder.MeasureString(listBox_Transactions.Items[i].ToString(), listBox_Transactions.Font).Widthする可能性がある理由を検索しましたが、見つかりませんでした。何か案は?

4

1 に答える 1

1

確かに知るのは難しいです.悲しいことに、私がこれを書いているとき、コメントとして説明を求めるのに必要な評判はありません.

私はあなたのコードを試してみましたが、うまくいきました。私が考えることができるのは、別の 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()

うまくいけば、これは役に立ちます。

于 2013-02-04T15:52:20.170 に答える