如何在我的ViewModel中从ListView获取SelectedItems [英] How to get SelectedItems from ListView in my ViewModel

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

问题描述

可能重复:
绑定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中设置我的RelayCommandDelegateCommand以期望类型为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆