管理多个选择与MVVM [英] Managing multiple selections with MVVM

查看:156
本文介绍了管理多个选择与MVVM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的旅程,学习MVVM我已经建立WPF和视图模型模式的一些基本的了解。我用下面的抽象提供了一个列表,并有兴趣在一个选定的项目时。

On my journey to learning MVVM I've established some basic understanding of WPF and the ViewModel pattern. I'm using the following abstraction when providing a list and am interested in a single selected item.

public ObservableCollection<OrderViewModel> Orders { get; private set; }
public ICollectionView OrdersView
{
    get
    {
    	if( _ordersView == null )
    		_ordersView = CollectionViewSource.GetDefaultView( Orders );
    	return _ordersView;
    }
}
private ICollectionView _ordersView;

public OrderViewModel CurrentOrder 
{ 
    get { return OrdersView.CurrentItem as OrderViewModel; } 
    set { OrdersView.MoveCurrentTo( value ); } 
}

然后我可以一起在WPF支持排序和筛选到一个列表绑定OrdersView:

I can then bind the OrdersView along with supporting sorting and filtering to a list in WPF:

<ListView ItemsSource="{Binding Path=OrdersView}" 
          IsSynchronizedWithCurrentItem="True">

这个作品真的很好单一选择的看法。但我想还支持多重选择在视图中,并有模型绑定到选定的项目列表。

This works really well for single selection views. But I'd like to also support multiple selections in the view and have the model bind to the list of selected items.

我将如何ListView.SelectedItems绑定到视图模型靠山物业?

How would I bind the ListView.SelectedItems to a backer property on the ViewModel?

推荐答案

这是我见过的约什 - 史密斯做的。

添加一个IsSelected属性为您的孩子视图模型( OrderViewModel 你的情况):

Add an IsSelected property to your child ViewModel (OrderViewModel in your case):

public bool IsSelected { get; set; }

(在此情况下为列表框)的容器上的所选属性绑定到这样的:

Bind the selected property on the container to this (for ListBox in this case):

<ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
    </Style>
</ListBox.ItemContainerStyle>

IsSelected被更新到相应字段匹配的容器上。

IsSelected is updated to match the corresponding field on the container.

您可以通过以下操作得到的视图模型所选孩子:

You can get the selected children in the view model by doing the following:

public IEnumerable<OrderViewModel> SelectedOrders
{
    get { return Orders.Where(o => o.IsSelected); }
}

这篇关于管理多个选择与MVVM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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