DataGrid Reuse Column Definitions

Aug 28, 2008 at 3:06 PM
Hi,

Is it possible to move column definitions to a resource that I can use from multiple wpf datagrids?  My scenario is that I have many grids with different data sources, but I would like to reuse the same column definitions.  I understand how I may do this using a user control, but I would like to try and do this in XAML without a user control if possible.  Here is some pseudo-code to illustrate what I would like:

Grid 1
 <dg:DataGrid ItemsSource="{Binding Source={StaticResource myDataSource1}}"
                                        AutoGenerateColumns="False">
<dg:DataGrid.Columns>
    <..... Point to some reusable column definition here....>
    </dg:DataGrid.Columns>
</dg:DataGrid>

Grid 2
 <dg:DataGrid ItemsSource="{Binding Source={StaticResource myDataSource2}}"
                                        AutoGenerateColumns="False">
<dg:DataGrid.Columns>
    <..... Point to some reusable column definition here....>
    </dg:DataGrid.Columns>
</dg:DataGrid>

Is something like this possible in some way?  Conceptually to me it is a ColumnsTemplate.

Thanks,
Jon




Coordinator
Aug 28, 2008 at 4:10 PM
Unfortunately you cannot reuse column definitions like this as they are hooked into the datagrid notification system which cannot work for multiple datagrids.  One sort of workaround you can do is use the AutoGeneratingColumns and AutoGeneratedColumns events to customize what the column definitions should be for your multiple datagrids.  You are still creating multiple sets of definitions but all the datagrids will get there column definitions from one place. 
Aug 28, 2008 at 8:15 PM
Hi Vin,

Thanks for the reply.  It sure would have been nice to do this somehow in XAML.  Thanks for the suggestion!
Jon
Dec 19, 2013 at 10:33 AM
Edited Dec 19, 2013 at 10:34 AM
I know it's an old question, but it turns up pretty high on Google and I have an ok solution.

You can inherit DataGrid and define the columns in xaml. Then you use the inherited type instead of DataGrid.

My specific example was
<DataGrid x:Class="...Controls.ImportDataGrid"  
           xmlns="...>
    <DataGrid.Columns>
        <DataGridTemplateColumn.../>
        ...
    </DataGrid.Columns>
</DataGrid>
and then using ImportDataGrid where I would use the DataGrid.