在ViewModel中获取WPF ListView.SelectedItems

NS.*_*.X. 13 .net data-binding wpf listview mvvm

有一些帖子讨论ListView.SelectedItems了为非平凡数量的代码添加数据绑定能力.在我的场景中,我不需要设置它ViewModel,只需获取选定的项目以便对它们执行操作并且它由命令触发,因此也不需要推送更新.

是否有一个简单的解决方案(在代码行方面),可能在代码隐藏?只要View并且ViewModel不需要互相引用,我就可以使用代码隐藏.我认为这是一个更通用的问题:" VM从按需查看数据的最佳实践 ",但我似乎找不到任何东西......

eva*_*anb 27

SelectedItems仅在执行命令时获取,然后使用CommandParameter并传入ListView.SelectedItems.

<ListBox x:Name="listbox" ItemsSource="{Binding StringList}" SelectionMode="Multiple"/>
<Button Command="{Binding GetListItemsCommand}" CommandParameter="{Binding SelectedItems, ElementName=listbox}" Content="GetSelectedListBoxItems"/>
Run Code Online (Sandbox Code Playgroud)

  • `SelectedItems`(复数)不支持数据绑定.请参阅[此链接](http://stackoverflow.com/questions/803216/managing-multiple-selections-with-mvvm)和[此链接](http://social.msdn.microsoft.com/forums/en-美国/ WPF /线程/ edd335ea-e5e1-48e1-91a2-793d613f5cc3 /).它也不能用作`CommandParameter`,我总是得到`null`,而使用`SelectedItem`(奇异)是好的. (4认同)

RAJ*_*RAJ 9

这可以使用如下的交互触发器来实现

  1. 您需要添加引用

    Microsoft.Expression.Interactions System.Windows.Interactivity

将以下xmlns添加到您的xaml中

xmlns:i="http://schemas.microsoft.com/expression//2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
Run Code Online (Sandbox Code Playgroud)

在GridView标记内添加以下代码

<GridView x:Name="GridName">
<i:Interaction.Triggers>
   <i:EventTrigger EventName="SelectionChanged">
       <i:InvokeCommandAction Command="{Binding Datacontext.SelectionChangedCommand, ElementName=YourUserControlName}" CommandParameter="{Binding SelectedItems, ElementName=GridName}" />
    </i:EventTrigger>
</i:Interaction.Triggers>
Run Code Online (Sandbox Code Playgroud)

ViewModel内部的代码在下面声明了属性

public DelegateCommand<object> SelectionChangedCommand {get;set;}
Run Code Online (Sandbox Code Playgroud)

在Viewmodel初始化Command的构造函数中,如下所示

SelectionChangedCommand = new DelegateCommand<object> (items => {
   var itemList = (items as ObservableCollection<object>).Cast<YourDto>().ToList();
}
Run Code Online (Sandbox Code Playgroud)