问题描述
我正在制作一个可通过自定义下一步"和后退"按钮和命令导航的 WPF 应用程序(即不使用 NavigationWindow
).在一个屏幕上,我有一个 ListBox
必须支持多项选择(使用 Extended
模式).我有这个屏幕的视图模型并将所选项目存储为属性,因为它们需要维护.
I am making a WPF application that is navigable via custom "Next" and "Back" buttons and commands (i.e. not using a NavigationWindow
). On one screen, I have a ListBox
that has to support multiple selections (using the Extended
mode). I have a view model for this screen and store the selected items as a property, since they need to be maintained.
但是,我知道 ListBox
的 SelectedItems
属性是只读的.我一直在尝试使用 这个解决方案来解决这个问题,但我无法将它应用到我的实现中.我发现我无法区分何时取消选择一个或多个元素以及何时在屏幕之间导航(在这两种情况下都会引发 NotifyCollectionChangedAction.Remove
,因为从技术上讲,在导航离开时所有选定的项目都会被取消选择从屏幕上).我的导航命令位于一个单独的视图模型中,该模型管理每个屏幕的视图模型,因此我无法在其中放置与带有 ListBox
的视图模型相关的任何实现.
However, I am aware that the SelectedItems
property of a ListBox
is read-only. I have been trying to work around the issue using this solution here, but I have not been able to adopt it into my implementation. I found that I can't differentiate between when one or more elements are deselected and when I navigate between screens (NotifyCollectionChangedAction.Remove
is raised in both cases, since technically all the selected items are deselected when navigating away from the screen). My navigation commands are located in a separate view model which manages the view models for each screen, so I can't put any implementation related to the view model with the ListBox
in there.
我发现了其他几个不太优雅的解决方案,但这些似乎都没有强制视图模型和视图之间的双向绑定.
I have found several other less elegant solutions, but none of these seem to enforce a two-way binding between the view model and the view.
任何帮助将不胜感激.如果有助于理解我的问题,我可以提供一些源代码.
Any help would be greatly appreciated. I can provide some of my source code if it would help to understand my problem.
推荐答案
尝试在每个数据项上创建一个 IsSelected
属性并将 ListBoxItem.IsSelected
绑定到该属性
Try creating an IsSelected
property on each of your data items and binding ListBoxItem.IsSelected
to that property
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
这篇关于如何在可导航的应用程序中支持 ListBox SelectedItems 与 MVVM 的绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!