且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF:绑定到 ListBoxItem.IsSelected 不适用于屏幕外项目

更新时间:2021-09-14 02:26:58

ListBox 默认情况下是 UI 虚拟化的.这意味着在任何给定时刻,只有 ItemsSource 中的可见项目(以及几乎可见"项目的一小部分)将实际呈现.这就解释了为什么更新 source 可以按预期工作(因为这些项目始终存在),但只是导航 UI 却不能(因为这些项目的视觉表示是动态创建和销毁的,并且永远不会同时存在.)

ListBox is, by default, UI virtualized. That means that at any given moment, only the visible items (along with a small subset of "almost visible" items) in the ItemsSource will actually be rendered. That explains why updating the source works as expected (since those items always exist,) but just navigating the UI doesn't (since the visual representations of those items are created and destroyed on the fly, and never exist together at once.)

如果您想关闭此行为,一种选择是在您的 ListBox 上设置 ScrollViewer.CanContentScroll=False.这将启用平滑"滚动,并隐式关闭虚拟化.要显式禁用虚拟化,您可以设置 VirtualizingStackPanel.IsVirtualizing=False.

If you want to turn off this behaviour, one option is to set ScrollViewer.CanContentScroll=False on your ListBox. This will enable "smooth" scrolling, and implicitly turn off virtualization. To disable virtualization explicitly, you can set VirtualizingStackPanel.IsVirtualizing=False.