DataGrid选择了列/单元格

时间:2011-03-26 15:05:29

标签: wpf silverlight datagrid master-detail

我通常使用下面的绑定/代码来同步MVVM类型的主 - 细节关联,利用CollectionViewSource。

对于DataGrid演示文稿,我有一组活动,这些活动是网格中的行。网格中的最后八列是Allocation.Amounts到给定Activity的集合。

我已经在网格中使用了代码,使用CurrentCellChanged事件,我在其中转换行的DataContext(到ActivityViewModel),然后使用网格的CurrentColumn属性来设置所选项目(SelectedAllocationVm)。它可以工作但是......

我可以做得更好吗?像我在下面为行做的事情?

的ViewModels

class diagram

DataGrid xaml绑定

<DataGrid 
    ItemsSource="{Binding ActivityVms}" 
    IsSynchronizedWithCurrentItem="True"
    ...               
    >

    <DataGrid.Columns>

        <ColumnSubclasses:TimeSheetTextColumn />

        <!-- Days of the Week -->
        <ColumnSubclasses:DayOfTheWeekColumn DowIndex="0" />
                      ...
        <ColumnSubclasses:DayOfTheWeekColumn DowIndex="6" />

        <ColumnSubclasses:DaysOfTheWeekColumnTotal />

    </DataGrid.Columns>

</DataGrid>

同步代码(ActivityCollectionViewModel)

    #region Detail View Models & Selected Item

    private ObservableCollection<ActivityViewModel> _activityVms;
    private ICollectionView _collectionView;

    void _setupCollections(ActivityCollectionComposite composite, IEntityValidator validator)
    {
        _activityVms = composite.ToActivityViewModels(validator);
        // react to additions & deletions to the list
        _activityVms.CollectionChanged += OnActivityCollectionChanged;

        // retrieve the ICollectionView associated with the ObservableCollection
        _collectionView = CollectionViewSource.GetDefaultView(_activityVms);
        if (_collectionView == null) throw new NullReferenceException("_collectionView");

        //listen to the CurrentChanged event to be notified when the selection changes
        _collectionView.CurrentChanged += OnCollectionViewCurrentChanged;
    }

    private void OnCollectionViewCurrentChanged(object sender, EventArgs e)
    {
        NotifyOfPropertyChange(() => SelectedActivityVm);
    }

    /// <summary>Returns a collection of all the view models we know about.</summary>
    public ObservableCollection<ActivityViewModel> ActivityVms
    {
        get { return _activityVms; }
    }

    public ActivityViewModel SelectedActivityVm
    {
        get {
            return _collectionView.CurrentItem as ActivityViewModel;
        }
    }

    #endregion

1 个答案:

答案 0 :(得分:0)

涡旋是对的; DataGrid列选择并不像使用CollectionViewSource管理所选列那么容易。