Avrohom Yisroel
Avrohom Yisroel

Reputation: 9472

Why is the ListBox's DesiredSize.Width always zero?

I am creating a custom control in C#, and want to have a grid cell that contains a ListBox, which can be hidden or shown as desired. Hiding it is easy, I just set the Width to zero, however when I want to show it, I need to know the width that the ListBox would like to use.

I thought that DesiredSize.Width would give me this vale, but it's always zero, even after calling Measure(). Here is the code I'm using to show the ListBox...

_lb.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
_lb.Width = _lb.DesiredSize.Width;

Any ideas how I find the desired width?

Upvotes: 3

Views: 1390

Answers (1)

Stewbob
Stewbob

Reputation: 16899

If your ListBox is in the cell of a grid, give that grid column a name. Then in code, you can access the .ActualWidth property of that grid column and use that value to set the width of your ListBox.

That assumes of course that the width of your grid column is not set to Auto, because that would still give you a 0 value.

_lb.Width = myGridColumn.ActualWidth

You might need to subtract a little bit from the column width to make your control fit nicely.

EDIT

One thing that I've found is that the ListBox must have items added to it before it will return anything other than 0 when it is measured.

string myItem = "Don't ask for a bath in Athabaska";
_lb.Items.Add(myItem);
_lb.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
double width = _lb.DesiredSize.Width;

As long as the ListBox has already been added to the window/usercontrol/grid, the above code returns a value of 227.53 for the width variable; using my defaults for font family and size.

If the ListBox has not been added to the window, or it doesn't have any items in it, it will return 0 for the .DesiredSize.Width property.

Also, if the .Visibility property is set to Collapsed instead of Hidden, the width will be 0.

Don't set the width to 0 when starting. Leave the width alone initially, set the .Visibility to Hidden. It will render to the needed width, but won't be shown. Then you can measure it and start playing around with the width.

Upvotes: 3

Related Questions