虚拟化堆栈面板MVVM +多重选择
我已经实现了一种类似于这篇文章中描述的选择模式,使用 ViewModel 来存储 IsSelected 值,并将 ListViewItem.IsSelected
绑定到 ViewModel IsSelected:
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
</Style>
</ListView.ItemContainerStyle>
它通常可以工作,但我遇到了一个严重的问题。通过使用 VirtualizingStackPanel 作为列表视图中的面板,仅创建可见的 ListViewItem。如果我使用“Ctrl+A”选择所有项目,或者在第一个项目上使用“Shift+Ctrl+End”等快捷组合,则所有项目都会被选中,但对于不可见的项目,ViewModel 不会获取其 IsSelected设置为 true。这是合乎逻辑的,因为如果未创建 ListViewItem
,绑定就无法工作。
有人遇到过同样的问题,并找到了解决方案(除了不使用 VirtualizingStackPanel 之外)?
I have implemented a selection pattern similar to the one described in this post using a ViewModel to store the IsSelected value, and by binding the ListViewItem.IsSelected
to the ViewModel IsSelected:
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
</Style>
</ListView.ItemContainerStyle>
It works in general, but I encounter a severe problem. By using the a VirtualizingStackPanel
as the panel in the list view, only the visible ListViewItem
are getting created. If I use "Ctrl+A" to select all items, or by using shortcut combination such "Shift+Ctrl+End" on the first item, all items get selected, but for the non visible items, the ViewModel does not get its IsSelected set to true. That is logical, because if the ListViewItem
are not created, the binding can't work.
Anybody experienced the same issue, and found a solution (apart from not using a VirtualizingStackPanel
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我在 MVVM 模式中找到了另一种处理选择的方法,它解决了我的问题。不是在视图模型中维护选择,而是从 ListView/ListBox 中检索选择,并将其作为参数传递给命令。一切都在 XAML 中完成:
在我的 ViewModel 中:
I found another way of handling selection in the MVVM pattern, which solved my issue. Instead of maintaining the selection in the viewmodel, the selection is retrieved from the ListView/ListBox, and passed as a parameter to the Command. All done in XAML:
in my ViewModel:
就我而言,我最终通过从 ListBox 派生 ListBoxEx 类并添加代码来响应选择更改、在项目视图模型上强制选择状态来解决此问题:
In my case, I ended up solving this by deriving a ListBoxEx class from ListBox, and adding code to respond to selection changes, enforcing the selection state on the item view models:
除了不使用 VirtualizingStackPanel 之外,我唯一能想到的就是捕获这些键盘快捷键并提供修改特定范围的 ViewModel 项的方法,以便它们的
>IsSelected
属性设置为True
(例如,SelectAll()
、SelectFromCurrentToEnd()
)。基本上绕过ListViewItem
上的Binding
来控制此类情况的选择。Apart from not using
VirtualizingStackPanel
, the only thing I can think of is to capture those keyboard shortcuts and have methods for modifying a certain range of yourViewModel
items so that theirIsSelected
property is set toTrue
(e.g.,SelectAll()
,SelectFromCurrentToEnd()
). Basically bypassing theBinding
onListViewItem
for controlling the selection for such cases.