我有一个 ListBox 停靠在窗口的左侧,窗口的宽度应根据其内容调整大小。当我滚动列表框时,它的宽度会晃动并变得比应有的更宽。基本上我认为正在发生的事情是 ListBox 计算它所有子项的大小以确定它自己的大小,但似乎只评估实际在屏幕上的控件的可见性绑定(bind)(大概是出于性能原因)。结果是它错误地计算了屏幕外子项的大小,为隐藏控件保留了空间。
如果列表中的项目少于窗口高度(因此没有滚动条),则列表始终是正确的宽度,并且当您滚动到顶部或底部时它总是捕捉到正确的宽度。只有当滚动条位于中间某处时,宽度才错误。
我整个晚上都在努力解决这个问题,尝试各种重构,比如使用 DataTemplateSelector 来抽象掉对可见性绑定(bind)的需求,但我最终得到了我不满意的非常肮脏的解决方法。我想解决手头的实际问题而不是躲避它。任何指针将不胜感激。
在下面的示例中,列表似乎将自身调整为 Foo 和 Bar 的宽度。更改 StackPanel 的方向会导致其大小调整为 Foo 和 Bar 中较长者的宽度。希望这是有道理的。
<ListBox ItemsSource="{Binding Widgets}" DockPanel.Dock="Left">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Visibility="{Binding ShowFoo, Converter={StaticResource BoolToVisConverter}}" Text="{Binding Foo}" />
<TextBlock Visibility="{Binding ShowBar, Converter={StaticResource InverseBoolToVisConverter}}" Text="{Binding Bar}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
请您参考如下方法:
您所描述的效果与可见性绑定(bind)无关。
Essentially what I think is happening is that the ListBox calculates the size of all it's children to determine it's own size, but only seems to evaluate
visibility bindings forcontrols that are actually on the screen (presumably for performance reasons). The result is that it calculates the size of it's off-screen children incorrectly, reserving space for hidden controls.
这对我来说是正确的。这是出于性能原因而完成的。也称为 ListBox 的虚拟化。其他控件也继承了它,例如 DataGrid。
为了摆脱它,您可以使用通常的堆栈面板切换 VirtualizingStackPanel:
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
如果您有大量项目,您可能会或可能不会遭受性能损失,但这就是生活。如果你不喜欢这个,我建议你一开始就不要有这个要求。
