C# MVVM DataGrid Binding Strategies?
What is the difference between:
<DataGrid
ItemsSource="{Binding MyCollection}"
/>
and...
<CollectionViewSource x:Key="CollectionData" Source="{Binding MyCollection}"/>
...
<DataGrid
DataContext="{StaticResource CollectionData}"
ItemsSource="{Binding}"
/>
They both seem to work. The only difference is that the second snippet, I can't bind to the SelectedItem. So why would someone pick one strategy over the other? Why wouldn't someone just use 开发者_如何学运维the first snippet? Thanks.
MSDN states...
CollectionViewSource has a View property that holds the actual view and a Source property that holds the source collection.
CollectionViewSource seperates the actual collection from the view that is representing the collection. This give you the ability to change the visual structure of the visible collection (think filtering out certain items as you type) without actually changing the underlying collection. It is a wrapper around the actual collection containing the objects needing a visual representation. Bea has a great article about it.
In addition you'll notice the explicit wrapping taking place in the CollectionViewSource
in your second example...
Source="{Binding MyCollection}"
Then the CollectionViewCource
is now being bound to via the DataGrid
providing the seperation I mentioned earlier; whereas the collection was being bound to directly in your first example.
A CollectionViewSource has more features that an ObservableCollection or whatever IEnumerable
you use for your ItemsSource. For example, it has SortDescriptions that can allow you to group data. An example can be found here.
TLDR; its a more powerful data structure.
As an aside, provided IsSynchronizedWithCurrentItem is true on the DataGrid, you can bind to the SelectedItem by appending a slash i.e. {Binding /}
精彩评论