0
我通常使用下面的綁定/代碼來同步MVVM類型的主/從關聯,以利用CollectionViewSource。DataGrid選擇的列/單元格
對於DataGrid演示文稿,我有一組活動,它們是網格中的行。網格中的最後八列是給定活動的Allocation.Amounts集合。我使用CurrentCellChanged事件,其中我將該行的DataContext(到ActivityViewModel),然後使用網格的CurrentColumn屬性來設置選定的項目(SelectedAllocationVm),使用後面的代碼在網格中。它的作品,但...
我可以做得更好嗎?就像我在下面做的行一樣?
的ViewModels數據網格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
您可以改進的唯一一件事是在ActivityCollectionViewModel內添加SelectedActivity屬性。但是對於選定的DataGrid列來說並不那麼容易。 – vorrtex 2011-03-26 17:34:31
@vortex。嘿,有渦流。它從類圖中不是很明顯,因爲我將SelectedActivityVm顯示爲關聯,但它在那裏。是的,我找不出更簡單的東西!你爲什麼不把這個答案寫成答案,以便我可以接受它並關閉這個答案。乾杯 – Berryl 2011-03-27 01:05:18