C# wpf Datagrid 内容对齐中心通过代码

问题描述 投票:0回答:3

我生成一个数据网格并希望将内容居中。

这是我的代码:

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

它不起作用......但为什么?

c# wpf datagrid
3个回答
2
投票

DataGridCell 模板不使用 DataGrid 的 VerticalContentAlignment 和 HorizontalContentAlignment 属性。

有多种方法可以实现所需的对齐。看一下这里:DataGrid行内容垂直对齐

这是代码中的解决方案

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

1
投票
cellStyle = new Style(typeof(DataGridCell)) { Setters = { new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center) } };

tabelle.CellStyle = cellStyle;

0
投票

对于自动生成的列,AutoGenerateColumn 事件会为每个自动生成的列触发,而 AutoGenerateColumns 则会在所有列生成后触发。

Private Sub dataGrid_AutoGeneratedColumns(sender As Object, e As EventArgs) Handles dataGrid.AutoGeneratedColumns
          ' This event gets fired after all Columns have been autogenerated.
          Dim dataGrid As DataGrid = CType(sender, DataGrid)
          Dim cellStyle As Style
    
          For intI As Integer = 0 To dataGrid.Columns.Count - 1
             cellStyle = New Style With {
                        .TargetType = GetType(DataGridCell)
                    }
             cellStyle.Setters.Add(New Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center))
             dataGrid.Columns(intI).CellStyle = cellStyle
          Next
    End Sub 

这个问题的其他答案需要稍微不同的类型才能为我工作,或者不包括事件处理。

© www.soinside.com 2019 - 2024. All rights reserved.