Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid Columns in Style or resource

Tags:

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!

like image 272
Daniel Bişar Avatar asked Apr 19 '11 12:04

Daniel Bişar


2 Answers

x:Shared helps to avoid the exception MattS423 has got.

<Window.Resources>     <DataGridTextColumn x:Key="dgtcFirstName" x:Shared="False" Header="First Name" Binding="{Binding FirstName}"/>     <DataGridTextColumn x:Key="dgtcSecondName" x:Shared="False" Header="Second Name" Binding="{Binding SecondName}"/> </Window.Resources>  <Grid>     <StackPanel>         <DataGrid AutoGenerateColumns="False" Height="200" Name="dataGrid1" Width="200">             <DataGrid.Columns>                 <StaticResource ResourceKey="dgtcFirstName"/>                 <StaticResource ResourceKey="dgtcSecondName"/>             </DataGrid.Columns>         </DataGrid>         <DataGrid AutoGenerateColumns="False" Height="200" Name="dataGrid2" Width="200">             <DataGrid.Columns>                 <StaticResource ResourceKey="dgtcSecondName"/>                 <StaticResource ResourceKey="dgtcFirstName"/>             </DataGrid.Columns>         </DataGrid>     </StackPanel> </Grid> 

like image 108
IVerzin Avatar answered Sep 27 '22 02:09

IVerzin


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> 
like image 28
Wallstreet Programmer Avatar answered Sep 23 '22 02:09

Wallstreet Programmer