Michael Meyer
Michael Meyer

Reputation: 2184

Format XAML DataGrid Column Header with Checkbox

I am using MahApps Metro Style for formatting a WPF DataGrid.

<DataGrid x:Name="routes" ItemsSource="{Binding Routes}" AutoGenerateColumns="False" Style="{StaticResource AzureDataGrid}" CanUserAddRows="False" ColumnWidth="*" >
    <DataGrid.Columns>
          <DataGridCheckBoxColumn Binding="{Binding Active}" MaxWidth="80" ElementStyle="{DynamicResource MetroDataGridCheckBox}" EditingElementStyle="{DynamicResource MetroDataGridCheckBox}">
                <DataGridCheckBoxColumn.Header>
                     <CheckBox Name="chkSelectAllRoutes" Checked="chkSelectAllRoutes_Checked" Unchecked="chkSelectAllRoutes_Unchecked" IsChecked="True" ></CheckBox>
                 </DataGridCheckBoxColumn.Header>
           </DataGridCheckBoxColumn>

           <DataGridTemplateColumn MaxWidth="40">
                  <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                              <Button Click="btnSearchAtRoute_Click" Tag="{Binding Identifier}" >
                                        <iconPacks:Material Kind="MapMarkerPath" />
                              </Button>                                  
                        </DataTemplate>
                  </DataGridTemplateColumn.CellTemplate>
           </DataGridTemplateColumn>
                    
           <DataGridTextColumn Binding="{Binding Name}" IsReadOnly="True" Header="Name"/>
           <DataGridTextColumn Binding="{Binding Distance, StringFormat=N2}" IsReadOnly="True" Header="Distance in KM"/>
    </DataGrid.Columns>
</DataGrid>

The first column contains a CheckBox at header and item Level. The result is displayed in the screeshot below. The header checkbox is aligned left, while the item checkboxes are centered in the column.

enter image description here

How can I achieve that the header checkbox looks like the item checkboxes (aligned in the middle)?

Upvotes: 0

Views: 862

Answers (1)

thatguy
thatguy

Reputation: 22079

You can use a column header style to center the checkbox.

<DataGridCheckBoxColumn Binding="{Binding Active}" MaxWidth="80" ElementStyle="{DynamicResource MetroDataGridCheckBox}" EditingElementStyle="{DynamicResource MetroDataGridCheckBox}">

   <DataGridCheckBoxColumn.HeaderStyle>
      <Style TargetType="{x:Type DataGridColumnHeader}">
         <Setter Property="HorizontalContentAlignment" Value="Center"/>
      </Style>
   </DataGridCheckBoxColumn.HeaderStyle>

   <DataGridCheckBoxColumn.Header>
      <CheckBox Name="chkSelectAllRoutes" Checked="chkSelectAllRoutes_Checked" Unchecked="chkSelectAllRoutes_Unchecked" IsChecked="True" ></CheckBox>
   </DataGridCheckBoxColumn.Header>

</DataGridCheckBoxColumn>

Upvotes: 1

Related Questions