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?
Have not tried this but it can work: http://thibautvs.com/blog/?p=1775 "key point is to put the ListBox in a grid column having an “auto” size mode"
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.
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.
精彩评论