列表框"IsSelected"绑定仅部分工作

Nat*_*end 5 wpf binding listbox mvvm listboxitem

我有一个ListBox通过绑定动态填充(这在a中定义DataTemplate,这就是绑定有点不寻常的原因):

<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>
Run Code Online (Sandbox Code Playgroud)

每个ListBoxItemIsSelected属性绑定到一个IsSelected自定义对象上属性.

当我选择单个ListBoxItems时,绑定正常工作 - 自定义对象的IsSelected属性在我的ViewModel中更新.但是,如果我ListBoxItem使用Ctrl + A命令选择所有s,则只有当前可见的ListBoxItems(当前位于我的滚动视口中的那些)更新其ViewModel绑定.在前端,所有ListBoxItems似乎都被选中,ListBox.SelectedItems.Count容器上的属性ListBox显示所有项都被选中.

此外,当我使用Ctrl + A 滚动ListBox选择所有ListBoxItems 后,当每个ListBoxItem滚动到视图中时,绑定会成功更新.

为什么这种绑定似乎只是部分有效?IsSelectedListBoxItems可以同时选择大量数据时,是否有更好的方法来处理属性的绑定?

编辑: 此行为不会仅使用Ctrl + A命令发生 - 当使用shift +单击选择所有项目时,我得到相同的结果.

Viv*_*Viv 5

我想,你所看到的行为是由于VirtualizingStackPanel.IsVirtualizing这是True在默认情况下,当结合ItemsSourceListBox

如果您为例如设置ListBox如下:

<ListBox VirtualizingStackPanel.IsVirtualizing="False" SelectionMode="Extended" ItemsSource="{Binding DataContext.ResultList, RelativeSource={RelativeSource AncestorType=Window}}">
Run Code Online (Sandbox Code Playgroud)

要么

<ListBox ...>
  ...
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel />
    </ItemsPanelTemplate>
  </ListBox.ItemsPanel>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

然后您应该看到所有绑定的项目都相应IsSelected更新,使用Ctrl + A或Shift + ...

Count即使使用虚拟化,集合等属性也会报告正确的值,以适应计算所需的内容ScrollBar.Height.View-port之外的项目不会被渲染,因此在实际使用之前,没有任何绑定对它们有效.