我有一个 ListBox
我通过绑定(bind)动态填充(这在 DataTemplate
中定义,这就是绑定(bind)有点不寻常的原因):
<ListBox SelectionMode="Extended" ItemsSource="{Binding DataContext.ResultList, RelativeSource={RelativeSource AncestorType=Window}}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Object}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
每个
ListBoxItem
的IsSelected
属性绑定(bind)到 IsSelected
自定义对象的属性。当我选择个人
ListBoxItem
s,绑定(bind)工作正常 - 自定义对象的 IsSelected
属性在我的 ViewModel 中更新。但是,如果我选择所有 ListBoxItem
s 用 Ctrl+A 命令,只有当前可见的 ListBoxItem
s(当前在我的滚动视口(viewport)中的那些)更新它们的 ViewModel 绑定(bind)。在前端,所有 ListBoxItem
s 似乎已被选中,而 ListBox.SelectedItems.Count
容器上的属性 ListBox
显示所有项目都被选中。此外,当我滚动浏览
ListBox
全选后ListBoxItem
s 与 Ctrl+A,绑定(bind)成功更新时每个 ListBoxItem
滚动到 View 中。为什么这个绑定(bind)似乎只是部分起作用?有没有更好的方法来处理
IsSelected
的绑定(bind)?大量 ListBoxItems
时的属性可以同时选择吗?编辑:
此行为并非仅在使用 Ctrl+A 命令时才会发生 - 当使用 shift+click 选择所有项目时,我会得到相同的结果。
最佳答案
我认为您看到的行为是由于 VirtualizingStackPanel.IsVirtualizing
这是True
默认绑定(bind)到 ItemsSource
的 ListBox
例如,如果您设置您的 ListBox
如:
<ListBox VirtualizingStackPanel.IsVirtualizing="False" SelectionMode="Extended" ItemsSource="{Binding DataContext.ResultList, RelativeSource={RelativeSource AncestorType=Window}}">
或者
<ListBox ...>
...
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
那么你应该看到你所有的绑定(bind)项目都有他们的
IsSelected
使用 Ctrl+A 或 Shift + ... 进行相应更新Count
等属性即使使用虚拟化,集合也会报告正确的值,以适应诸如计算所需的 ScrollBar.Height
之类的事情。 .视口(viewport)之外的项目不会被渲染,因此在它们真正被使用之前没有绑定(bind)对它们生效。
关于wpf - 列表框 "IsSelected"绑定(bind)仅部分工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47179059/