使用MVVM管理多个选择 [英] Managing multiple selections with MVVM
问题描述
public ObservableCollection< OrderViewModel>订单{get;私人集合}
public ICollectionView OrdersView
{
get
{
if(_ordersView == null)
_ordersView = CollectionViewSource.GetDefaultView(Orders);
return _ordersView;
}
}
私人ICollectionView _ordersView;
public OrderViewModel CurrentOrder
{
get {return OrdersView.CurrentItem as OrderViewModel; }
set {OrdersView.MoveCurrentTo(value); }
}
然后我可以绑定OrdersView以及支持排序和过滤到列表在WPF中:
< ListView ItemsSource ={Binding Path = OrdersView}
IsSynchronizedWithCurrentItem =True> ;
这对单选视图效果很好。但是,我也希望在视图中支持多个选择,并将模型绑定到所选项目的列表。
如何将ListView.SelectedItem绑定到ViewModel上的支持属性?
以下是我见过的 Josh Smith 。
将一个IsSelected属性添加到您的孩子ViewModel( OrderViewModel
):
public bool IsSelected {get;组; }
将容器上的所选属性绑定到此(对于ListBox在这种情况下):
< ListBox.ItemContainerStyle>
< Style TargetType ={x:Type ListBoxItem}>
< Setter Property =IsSelectedValue ={Binding Mode = TwoWay,Path = IsSelected}/>
< / Style>
< /ListBox.ItemContainerStyle>
IsSelected更新为与容器上相应的字段相匹配。
您可以通过执行以下操作获取视图模型中的所选子项:
public IEnumerable< OrderViewModel> SelectedOrders
{
get {return Orders.Where(o => o.IsSelected); }
}
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 ); } }
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.
How would I bind the ListView.SelectedItems to a backer property on the ViewModel?
解决方案Here's what I've seen Josh Smith do.
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 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屋!