开发者

DataGrid selected column / cell

I typically use the bindings / code below to synchronize an MVVM type master-detail association, taking advantage of a CollectionViewSource.

For a DataGrid presentation I have a collection of Activities that are rows in the grid. The last eight columns in the grid are a collection of Allocation.Amounts to a given Activity.

I have resorted to using code behind in the grid, using the CurrentCellChanged event where I cast the DataContext of the row (to an ActivityViewModel) and then use the CurrentColumn property of the grid to set the selected item (SelectedAllocationVm). It works but...

Can I do better? Something like what I am doing below for rows?

ViewModels

DataGrid selected column / cell

DataGrid xaml bindings

<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>

synchronization code (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开发者_如何学Python { return _activityVms; }
    }

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

    #endregion


vortex was right; DataGrid column selection is not as easy as managing the selected column with a CollectionViewSource.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜