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;
};
cellStyle = new Style(typeof(DataGridCell)) { Setters = { new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center) } };
tabelle.CellStyle = cellStyle;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.