确定 ListBox 中最宽元素的宽度
当您没有显式设置 ListBox 的宽度时,它会自动将其宽度设置为其最宽的可见项目的宽度。这意味着当您上下滚动并且最宽的可见数据项发生变化时,列表框本身的宽度会增加和减少。
那么找到列表中最宽项目的宽度,然后将 ListBox 宽度设置为该宽度的最佳方法是什么?我的 ListBox 数据模板是一个包含 CheckBox 和 TextBlock 的 StackPanel,因此显然 Textblock 宽度会根据其中字符串的长度而变化。
这里已经有一些建议,答案范围从“猜测”到 “测量文本大小”(如何在 SL 中测量文本大小而不将其放置在 UI 元素中?)。
谁能给我一些想法吗?如果需要的话,我愿意迭代所有数据模板实例,尽管更好的选择可能是找到最长的字符串并从那里计算?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
还没有尝试过,但它可以工作:
http://thibautvs.com/blog/?p=1775
“关键点是将列表框放在具有“自动”大小模式的网格列中”
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 使用 VirtualizingStackPanel 作为默认 ItemsPanel。由于 VirtualizingStackPanel 仅为可见项目创建 UI 元素,因此您可能会看到您所描述的行为。要缓解此行为,您可以尝试设置 VirtualizingStackPanel.IsVirtualizing="False" 或将 ItemsPanel 更改为 StackPanel。
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.
对此进行的研究表明,如果不扩展/覆盖 ListBox 的范围,这是不可能的 - 设置 VirtualizingStackPanel 的
IsVirtualizing
属性没有效果。我必须采用的解决方案是以编程方式选择一个合适的宽度。
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.