I have 3 datagrids that share the same data type. I’d like to configure the column binding once and have the 3 datagrids share the resource.
e.g.
<DataGrid Grid.Row="1" x:Name="primaryDG" ItemsSource="{Binding Path=dgSource AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Width="Auto" Header="Column 1" Binding="{Binding Path=Col1}"/>
<DataGridTextColumn Width="Auto" Header="Column 2" Binding="{Binding Path=Col2}"/>
<DataGridTextColumn Width="Auto" Header="Column 3" Binding="{Binding Path=Col3}"/>
<DataGridTextColumn Width="Auto" Header="Column 4" Binding="{Binding Path=Col4}"/>
</DataGrid.Columns>
</DataGrid>
Is there a way to set the ItemsSource for each DataGrid, then use a datatemplate or controltemplate to get the columns?
Yes… two ways. One you can simply add a style for
DataGridthat sets the columns like this…That works but represents a problem if you are applying it to multiple grids that themselves may already be using a style.
In that case, the other, more flexible way works better. This however requires creating a XAML-friendly classes to represent an
ObservableCollection<DataGridColumn>(although you technically only said columns, I like to be complete myself so I’d also do one for the rows) Then add them in a place you can reference in the XAML namespaces. (I call minexmlns:dgefor ‘DataGridEnhancements’) You then use it like this:In the code somwhere (I’d make it accessible app-wide)…
Then in the resources…
And finally in the XAML…
HTH,
Mark
EDIT:
Since you cannot set the
DataGrid.Columnsproperty, you need to enhance yourDataGridView(as mentioned in the comments). Here is the code for anEnhancedDataGrid:Now you could set the columns with the SetColumns dependency property created in your CustomControl: