views:

38

answers:

2

When you do not explicitly set the width of a ListBox, it will automatically set its width to the width of its widest visible item. This means that as you scroll up and down and the widest visible data item changes, the width of the listbox itself increases and decreases.

So what is the best way to find the width of the widest item in the list, and then set the ListBox width to that? My data template for the ListBox is a StackPanel containing a CheckBox and a TextBlock, so obviously the Textblock width will vary according to the length of the string in it.

There are a couple of suggestions already here on SO, with answers ranging from "take a guess" to "measure the text size" (how do you measure text size in SL without placing it in a UI element?).

Can anyone throw me a few ideas? I am open to iterating all the data template instances if i have to, although a better option may be to find the longest string and calculate from there?

A: 

ListBox uses VirtualizingStackPanel as default ItemsPanel. Because VirtualizingStackPanel creates UI elements only for visible items you might see the behavoir you describe. To mitigate this behaviour you could try to set VirtualizingStackPanel.IsVirtualizing="False" or change ItemsPanel to StackPanel.

Denis
A: 

Messing around with this has shown me that it isn't possible without going to the extent of extending/overrideing the ListBox - setting the IsVirtualizing property of the VirtualizingStackPanel had no effect.

The solution that i had to go with was to programmatically choose a good width.

slugster