本文介绍了在ViewModel中获取WPF ListView.SelectedItems的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些帖子讨论了使用非常小的代码量为 ListView.SelectedItems 添加数据绑定功能。在我的情况下,我不需要从 ViewModel 中设置它,只需获取所选项目,以便对它们执行操作,并由命令触发,因此推送更新也是不必要。

There are some posts discussing adding data-binding ability for ListView.SelectedItems with non-trivial amount of code. In my scenario I don't need to set it from the ViewModel, just getting selected items in order to perform action on them and it is triggered by command so push update is also not necessary.

有没有一个简单的解决方案(代码行),也许在代码隐藏?只要 View ViewModel 不需要引用对方,代码隐藏就好了。我认为这是一个更通用的问题:最佳实践为VM从View On-demand 获取数据,但我似乎找不到任何东西...

Is there a simple solution (in terms of lines of code), maybe in code-behind? I am fine with code-behind as long as View and ViewModel don't need to reference each other. I think this is a more generic question: "best practice for VM to get data from the View on-demand", but I can't seem to find anything...

推荐答案

只有执行命令才能获取 SelectedItems ,然后使用 CommandParameter 并传入 ListView.SelectedItems

To get the SelectedItems only when a command is executed then use CommandParameter and pass in the ListView.SelectedItems.

<ListBox x:Name="listbox" ItemsSource="{Binding StringList}" SelectionMode="Multiple"/>
<Button Command="{Binding GetListItemsCommand}" CommandParameter="{Binding SelectedItems, ElementName=listbox}" Content="GetSelectedListBoxItems"/>

这篇关于在ViewModel中获取WPF ListView.SelectedItems的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 02:10