如何在我的ViewModel中从ListView获取SelectedItems [英] How to get SelectedItems from ListView in my ViewModel
问题描述
可能重复:
绑定Listview的SelectedItems
Possible Duplicate:
Binding SelectedItems of Listview
我有一个ListView,用户可以选择多个项目.我需要获取在我的视图模型中从ListView中选择的项目的列表.
I have a ListView and User can select multiple items. I need to get list of items selected from ListView in my View Model.
请建议从ListView获取SelectedItems.
please suggest to get SelectedItems from ListView.
谢谢
推荐答案
我通常有两种方法
如果我只想知道为命令目的选择了什么,我将在ViewModel
中设置我的RelayCommand
或DelegateCommand
以期望类型为IList<SomeClass>
的参数并传递ListView.SelectedItems
输入为CommandParameter
If I only need to know what is selected for the purpose of a command, I will setup my RelayCommand
or DelegateCommand
in the ViewModel
to expect a parameter of type IList<SomeClass>
and pass the ListView.SelectedItems
in as the CommandParameter
<Button Command="{Binding SomeCommand}"
CommandParameter="{Binding ElementName=MyListView, Path=SelectedItems}" />
我经常使用的另一种方法是在ListView
中使用的任何数据项上创建IsSelected
属性,并将其绑定到ListViewItem.IsSelected
属性
The other method I often use is to create an IsSelected
property on whatever data item is being used in the ListView
, and bind it to the ListViewItem.IsSelected
property
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
然后我的ViewModel
可以通过查看其IsSelected
属性来确定是否选择了该项目
Then my ViewModel
can find out if an item is selected or not by looking at it's IsSelected
property
foreach(var item in MyCollection)
{
if (item.IsSelected)
// Do work
}
这篇关于如何在我的ViewModel中从ListView获取SelectedItems的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!