tags:

views:

38

answers:

1

I'll start out by saying that I'm trying to follow MVVM as strictly as I can, so I'd like to do the following using Binding only.

I have multiple DataGrids showing different ObservableCollections of the same data type. How can I define once which columns, and their Binding paths, will show on all of the DataGrids?

It doesn't appear that I can set a Style for DataGrid.Column. The goal is that all of the DataGrids show the same DataGrid.Column information, but with only having to maintain one copy of it.

Any ideas?

+1  A: 

Define your DataGrid as a Resource.

Then, you can "reference" the DataGrid in multiple areas of your Window or Application like this:

<ContentControl Content="{StaticResource myDataGrid}"></ContentControl>

You can change the DataContext of the ContentControl so that the DataGrids will be bound to different data sources.

ChrisNel52
Just to clarify, in the above sample code I'm assuming the DataGrid has a Key of 'myDataGrid'.
ChrisNel52
How could I set parameters that may differ among the DataGrids, such as HeadersVisibility?
bufferz
Option 1: If the HeadersVisibility value is determined by a bound property, than bind the HeadersVisibility to the appropriate property and use a ValueConverter to convert the property value to the correct HeadersVisiblity value.Option 2: Create a UserControl instead of defining the DataGrid as a Resource. Inside your UserControl, define your DataGrid and some dependency properties that can be used to set the correct HeadersVisibility value.
ChrisNel52
From playing around with both options, #2 felt less hackish. It was still a lot of work, but it's actually easier for me to to maintain several similar similar DataGrids than to define a UserControl since there are still many differing parameters. I thought there may perhaps be a middle ground, but it looks like not. I think a UserControl is the cleanest way to go however, even if the common properties are few. Thank you for the help Chris!
bufferz