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?
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;
};