wpf - 列表框 "IsSelected"绑定(bind)仅部分工作

标签 wpf mvvm binding listbox listboxitem

我有一个 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>

每个ListBoxItemIsSelected属性绑定(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)到 ItemsSourceListBox
例如,如果您设置您的 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/

相关文章:

c# - WPF:使用 GridSplitter 隐藏网格行

c# - WPF MVVM 案例 : ItemsControl contains hyperlink and command to update property in ViewModel

text - UWP 中 'TextBlock' 的绑定(bind)部分

WPF-MVVM 将 ViewModel-Property 绑定(bind)到嵌套的 UserControl

c# - 如何从 View 模型访问不可绑定(bind)的 View 属性?

c# - 什么是 WPF 应用程序服务

c# - 从模型中添加新项目计数

c# - WPF DataGrid显示有限的行数并在该数后滚动

c# - 为wpf mvvm应用程序设置字体系列的用户首选项

c# - 串联列表中的项目以在 WPF 组合框 Itemssource 中使用