wpf 数据网格单元格格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27197852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:44:58  来源:igfitidea点击:

wpf Datagrid Cell Formatting

c#wpfdatagrid

提问by CT Dev

Being completely novice to wpf, I am trying to get a datagrid cell formatted. I've found the following code and am playing with it, however, it does not do anything.

作为 wpf 的新手,我正在尝试格式化数据网格单元格。我找到了以下代码并正在使用它,但是,它没有做任何事情。

In this example, all I want to do is to format the columns that have a date in them. Could someone point me in the right direction???

在这个例子中,我想要做的就是格式化包含日期的列。有人能指出我正确的方向吗???

My datagrid source is bound to a datatable in the code behind.

我的数据网格源绑定到后面代码中的数据表。

Please mindful that I may be using the wrong method to achieve my goal, so if you can advise what method to use(in case the AutoGeneratingColumn is wrong)...

请注意,我可能使用了错误的方法来实现我的目标,所以如果您能建议使用哪种方法(以防 AutoGeneratingColumn 错误)...

Thanks in advance.

提前致谢。

private void DataGridBugLog_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    Style styleCenter = new Style(typeof(DataGridCell));
    style.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Center));
    style.Setters.Add(new Setter(FontWeightProperty, "Bold"));
    style.Setters.Add(new Setter(ForegroundProperty, "Red"));

    if (e.PropertyType == typeof(System.DateTime))
    {
        (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";
        (e.Column as DataGridTextColumn).CellStyle = styleCenter;
    }
}

回答by Eben

Your style.Setters.Addshould be styleCenter.Setters.Add.

style.Setters.Add应该是styleCenter.Setters.Add

Your "Bold"should be FontWeights.Bold, and also "Red"should be Brushes.Red, you can use string in the xaml side as it can convert string to the type, while from code-behind, you need set the type.

您的“Bold”应该是FontWeights.Bold“Red”也应该是Brushes.Red,您可以在 xaml 端使用字符串,因为它可以将字符串转换为类型,而在代码隐藏中,您需要设置类型。

The code below works for me as expected (but I would extract the Style if need to be reused for other cells)

下面的代码按预期对我有用(但如果需要为其他单元格重用,我会提取样式)

if (e.PropertyType == typeof(System.DateTime))
{
    Style styleCenter = new Style(typeof(DataGridCell));

    styleCenter.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Center));
    styleCenter.Setters.Add(new Setter(FontWeightProperty, FontWeights.Bold));
    styleCenter.Setters.Add(new Setter(ForegroundProperty, Brushes.Red));

    (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";
    (e.Column as DataGridTextColumn).CellStyle = styleCenter;
}