Search code examples
c#wpfxamlwpfdatagrid

Can I add specific columns to all DataGrids without using code?


I know I can do this in XAML to add a column to a specific DataGrid.

<DataGrid x:Name="grid">
    <DataGrid.Columns>
        <DataGridTextColumn></DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

I also know that I can do the same in code.

DataGridColumn dwa = new DataGridCheckBoxColumn ();
grid.Columns.Add (dwa);

But is it possible to do this using XAML and apply it to all DataGrids? I can apply styles using a ResourceDictionary but I don't know about this.


Solution

  • Because the Columns property is readonly. So using a Style cannot set it (via Setter) as well as somehow add a DataGridColumn to it. That means you would be stuck that way. However there is a workaround, instead of using multi DataGrids in your window, you can just use multi Controls, then add some Style targeting Control type and set the Template to a DataGrid. Here is a simple example:

    <Grid>  
      <Grid.Resources>
         <Style TargetType="Control">
           <Setter Property="Template">
             <Setter.Value>
               <ControlTemplate>
                   <DataGrid>
                      <DataGrid.Columns>
                         <DataGridTextColumn Header="Name"></DataGridTextColumn>
                         <DataGridTextColumn Header="City"></DataGridTextColumn>
                      </DataGrid.Columns>
                   </DataGrid>
               </ControlTemplate>
             </Setter.Value>
           </Setter>
         </Style>
      </Grid.Resources>
      <Grid.RowDefinitions>
         <RowDefinition/>
         <RowDefinition/>
         <RowDefinition/>
      </Grid.RowDefinitions>
      <!-- use 3 controls instead of 3 DataGrids -->
      <Control></Control>
      <Control Grid.Row="1"></Control>
      <Control Grid.Row="2"></Control>
    </Grid>
    

    My advice is try building some view model, then you just need to assign the ItemsSource (which can be set via a Style Setter), of course that way we have to use the default AutoGenerateColumns feature of the DataGrid.