有一些帖子讨论为 ListView.SelectedItems
添加数据绑定(bind)功能具有非平凡的代码量。在我的场景中,我不需要从 ViewModel
设置它,只是获取选定的项目以便对它们执行操作,它是由命令触发的,因此也不需要推送更新。
是否有一个简单的解决方案(就代码行而言),也许在代码隐藏中?只要View
,我就可以使用代码隐藏了和 ViewModel
不需要互相引用。我认为这是一个更通用的问题:“VM 从按需查看数据的最佳实践”,但我似乎找不到任何东西......
最佳答案
这可以使用交互触发器来实现,如下所示
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"
在您的 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>
ViewModel 中的代码在下面声明属性
public DelegateCommand<object> SelectionChangedCommand {get;set;}
在 Viewmodel 的构造函数中初始化命令如下
SelectionChangedCommand = new DelegateCommand<object> (items => {
var itemList = (items as ObservableCollection<object>).Cast<YourDto>().ToList();
}
关于.net - 在 ViewModel 中获取 WPF ListView.SelectedItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10964910/