【问题标题】:C# wpf Datagrid content alignment center via codeC# wpf Datagrid 内容对齐中心通过代码
【发布时间】:2016-10-09 01:37:54
【问题描述】:

我生成了一个 Datagrid 并希望将内容居中。

这是我的代码:

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

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

【问题讨论】:

  • “不起作用”是什么意思?你看到了什么?
  • 内容未居中。如果我删除最后两行,我会得到相同的结果
  • 你通过代码来做这件事有什么原因吗?在 XAML 中,您可以更轻松地应用选项。风格。另外,我假设您使用的是 MVVM 或 MVC,因为您定义了 ViewModel
  • 我是 wpf 的新手。我不知道如何通过 xaml 动态生成一些东西,所以我通过代码做到了。而且我认为它应该有效,但不是我尝试的方式。

标签: c# wpf datagrid


【解决方案1】:
cellStyle = new Style(typeof(DataGridCell)) { Setters = { new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center) } };

tabelle.CellStyle = cellStyle;

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

DataGridCell 模板不使用 DataGrid 的 VerticalContentAlignment 和 Horizo​​ntalContentAlignment 属性。

有多种方法可以获得所需的对齐方式。看这里:DataGrid row content vertical alignment

这是代码中的解决方案

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

【讨论】:

    猜你喜欢
    • 2011-02-22
    • 2014-08-02
    • 2011-04-28
    • 2013-07-10
    • 1970-01-01
    • 2014-06-07
    • 2010-11-09
    • 1970-01-01
    • 2011-06-04
    相关资源
    最近更新 更多