Text alignment in a WPF DataGrid

后端 未结 13 736
野性不改
野性不改 2020-12-14 14:13

How can I align the column data to center in a WPF DataGrid?

13条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 14:22

    Thanks Danny Beckett for converting @MohammedAFadil's XAML answer, converted to C# code. All of my datagrids are set up dynamically, so I can change anything, whenever.

    To set up an empty datagrid, with nothing in it and then just bind it to data, just take your datagrid.columns

            var centerTextSetter = new Style(typeof(DataGridCell))
            {
                Setters = { new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center) }
            };
            DgDbNames.Columns.Add(new DataGridTextColumn()
            {
                Header = "Db Name",
                Binding = new System.Windows.Data.Binding("DbName"),
                IsReadOnly = true,
                Width = new DataGridLength(0.2, DataGridLengthUnitType.Star),
                CellStyle = centerTextSetter
            });
    

提交回复
热议问题