Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#wpf Datagrid内容对齐中心通过代码_C#_Wpf_Datagrid - Fatal编程技术网

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

C#wpf Datagrid内容对齐中心通过代码,c#,wpf,datagrid,C#,Wpf,Datagrid,我生成一个Datagrid,并希望将内容集中 这是我的代码: DataGrid tabelle = new DataGrid(); tabelle.ItemsSource = dt.DefaultView; tabelle.RowHeight = 50; tabelle.VerticalContentAlignment = VerticalAlignment.Center; tabelle.HorizontalContentAlignment = HorizontalAlignment.Cent

我生成一个Datagrid,并希望将内容集中

这是我的代码:

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

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

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

有几种方法可以获得所需的对齐。请看这里:

下面是一个代码解决方案

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

“不行”是什么意思?你看到了什么?内容没有居中。如果我删除最后两行,我会得到相同的结果。你为什么要通过代码来做这件事?在XAML中,您可以更容易地应用诸如样式之类的选项。另外,我假设您使用的是MVVM或MVC,因为您的ViewModel definedim是wpf的新版本。我不知道如何通过xaml动态生成一些东西,所以我是通过代码来实现的。我认为它应该起作用,但不是我尝试的方式。