Alex Rivera | Logout

WPF DataGrid Columns in Style or resource

Asked 2011-04-19T12:11:34.960
23

Is it possible to declare DataGrid columns in a style or as a resource? I would like to do something like this:

<....Resources>
    <DataGridColumns x:Key="dgcDataGridColumns">
        <DataGridTextColumn />
        <DataGridTextColumn />
    </DataGridColumns
</....Resources>

<DataGrid Columns="{StaticResource dgcDataGridColumns}" />

The reason is that i have to share the column definition for 4 different DataGrids. Any way to achieve this? Best would be without code behind!

Edit
Report

1 Answer

24

Columns property of the DataGrid has no setter so it is not possibly. You can however do something like this:

<Window.Resources>

    <Controls:DataGrid x:Key="PersonDataGrid" AutoGenerateColumns="False" ItemsSource="{Binding .}" x:Shared="False">
        <Controls:DataGrid.Columns>
            <Controls:DataGridTextColumn Header="First Name" Binding="{Binding Path=FirstName}" IsReadOnly="True"/>
            <Controls:DataGridTextColumn Header="Last Name" Binding="{Binding Path=LastName}" IsReadOnly="True"/>
        </Controls:DataGrid.Columns>
    </Controls:DataGrid>

</Window.Resources>

<StackPanel>
    <ContentControl Content="{StaticResource PersonDataGrid}" DataContext="{Binding Path=Customers}"></ContentControl>
    <ContentControl Content="{StaticResource PersonDataGrid}" DataContext="{Binding Path=Employees}"></ContentControl>
</StackPanel>
answered 2011-04-19T13:34:27.627

Your Answer