Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 227
JP Richardson Avatar asked Oct 13 '22 19:10

JP Richardson


1 Answers

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.

like image 190
Aaron McIver Avatar answered Nov 12 '22 20:11

Aaron McIver