1

I generate a Datagrid and want to center the content.

this is my code:

DataGrid tabelle = new DataGrid();
tabelle.ItemsSource = dt.DefaultView;
tabelle.RowHeight = 50;
tabelle.VerticalContentAlignment = VerticalAlignment.Center;
tabelle.HorizontalContentAlignment = HorizontalAlignment.Center;

It doesnt work... but why?

Plender
  • 15
  • 3
  • What do you mean 'doesn't work'? What do you see instead? – Tyler Lee Jun 08 '16 at 16:46
  • the content is not centered. I get the same result if I delete the last two lines – Plender Jun 08 '16 at 16:48
  • Is there a reason you are doing it through code? in XAML, you have more easy to apply options ex. Style. Also, I assume u are using MVVM or MVC since you have ViewModel defined – Kamil Solecki Jun 08 '16 at 17:04
  • im new to wpf. i dont know how to generate something dynamically via xaml, so i did it via code. And i think it should work, but not the way i tried. – Plender Jun 08 '16 at 17:12

1 Answers1

2

DataGridCell template does not use VerticalContentAlignment and HorizontalContentAlignment properties of DataGrid.

There are ways to get desired alignment. Take a look here: DataGrid row content vertical alignment

here is a solution in code

DataGrid tabelle = new DataGrid();
tabelle.ItemsSource = dt.DefaultView;
tabelle.RowHeight = 50;

// cell style with centered text
var cellStyle = new Style
                {
                    TargetType = typeof (TextBlock),
                    Setters =
                    {
                        new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center),
                        new Setter(TextBlock.VerticalAlignmentProperty, VerticalAlignment.Center),
                    }
                };

// assign new style for text columns when they are created
tabelle.AutoGeneratingColumn += (sender, e) =>
{
    var c = e.Column as DataGridTextColumn;
    if (c != null)
        c.ElementStyle = cellStyle;
};
Community
  • 1
  • 1
ASh
  • 30,500
  • 9
  • 48
  • 72