Search code examples
wpfdatagridstylesalignmentdatagridtextcolumn

DataGridTextColumn is highlighted only on textblock when selected after defining an alignemnt


I have a datagrid which I define the styles and columns in code behind as following :

My_Data_Grid.ItemsSource = an_observableCollection ;
Style my_Style = new System.Windows.Style(typeof(DataGridCell));
DataGridTextColumn a_Column = new DataGridTextColumn();
a_Column.Header = "_Header_";
a_Column.Binding = new Binding("index");
a_Column.Width = 80;
a_Column.CellStyle = my_Style;
My_Data_Grid.Columns.Add(a_Column);

This snippet code will have a result like the following screenshot :

enter image description here

I want to change the alignment, so that I apply the following changes to previous code :

my_Style.Setters.Add(
            new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center));
my_Style.Setters.Add(
            new Setter(TextBlock.VerticalAlignmentProperty, VerticalAlignment.Center));

The effect will be the following screenshot :

enter image description here

As you notice, the alignment is fine now; but the selection is not the whole cell any more ! only the text is highlighted as selected !

Doest any one has any ideas how I can fix this problem ?


Solution

  • The problem in your code is, that a TextBlock has no built-in support for vertical content alignment. To align the content inside your cells, you would have to overwrite the CellTemplate for the corresponding columns and set the vertical alignment on a wrapping grid or border. Add this code to a resource dictionary:

    <Style x:Key="CenteredCellStyle"
            TargetType="{x:Type DataGridCell}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridCell}">
                    <Grid Background="{TemplateBinding Background}">
                        <ContentPresenter VerticalAlignment="Center" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    

    Use as

    My_Data_Grid.ItemsSource = an_observableCollection ;
    Style my_Style = Application.Current.FindResource("CenteredCellStyle") as Style;
    DataGridTextColumn a_Column = new DataGridTextColumn();
    a_Column.Header = "_Header_";
    a_Column.Binding = new Binding("index");
    a_Column.Width = 80;
    a_Column.CellStyle = my_Style;
    My_Data_Grid.Columns.Add(a_Column);
    

    See: DataGrid row content vertical alignment