【转】将Datagrid的SelectedItems输出到ViewModel的友好MVVM方式

原文地址:http://geekswithblogs.net/lbugnion/archive/2010/05/19/handling-datagrid.selecteditems-in-an-mvvm-friendly-manner.aspx

An interesting question from one of the MVVM Light users today:

Is there an MVVM-friendly way to get a DataGrid’s SelectedItems into the ViewModel?

The issue there is as old as the DataGrid (that’s not very old but still): SelectedItem (singular) is a DependencyProperty and can be databound to a property in the ViewModel. SelectedItems (plural) is not a DependencyProperty.

Thankfully the answer is very simple: Use EventToCommand to call a Command in the ViewModel, and pass the SelectedItems collection as parameter. For example, if the command in the ViewModel is declared as follows:

 

public RelayCommand<IList> SelectionChangedCommand
{
get;
private set;
}

 

and (in the MainViewModel constructor):

 1 SelectionChangedCommand = new RelayCommand<IList>(
 2 items =>
 3 {
 4 if (items == null)
 5 {
 6 NumberOfItemsSelected = 0;
 7 return;
 8 }
 9 
10 NumberOfItemsSelected = items.Count;
11 });

 

Then the XAML markup becomes:

<sdk:DataGrid x:Name="MyDataGrid"
ItemsSource="{Binding Items}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cmd:EventToCommand
Command="{Binding SelectionChangedCommand}"
CommandParameter="{Binding SelectedItems,
ElementName=MyDataGrid}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</sdk:DataGrid>

 

I slapped a quick sample and published it here (VS2010, SL4 but the concept works in SL3 and WPF too).

转载于:https://www.cnblogs.com/jojinshallar/articles/3288741.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值