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

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

问题描述

在学习 MVVM 的过程中,我对 WPF 和 ViewModel 模式有了一些基本的了解.我在提供列表时使用了以下抽象,并且对单个选定项目感兴趣.

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 ); } 
}

然后,我可以将 OrdersView 与支持排序和过滤功能一起绑定到 WPF 中的列表:

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 绑定到 ViewModel 上的支持者属性?

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

推荐答案

IsSelected 属性添加到您的子 ViewModel(在您的情况下为 OrderViewModel):

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

public bool IsSelected { get; set; }

将容器上的 selected 属性绑定到 this(在本例中为 ListBox):

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天全站免登陆