简体   繁体   English

wpf Datagrid单元格格式化

[英]wpf Datagrid Cell Formatting

Being completely novice to wpf, I am trying to get a datagrid cell formatted. 作为WPF的新手,我正在尝试格式化DataGrid单元格。 I've found the following code and am playing with it, however, it does not do anything. 我找到了以下代码并正在使用它,但是,它没有任何作用。

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. 我的datagrid源绑定到后面代码中的数据表。

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

Your style.Setters.Add should 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. 您的“粗体”应该是FontWeights.Bold“红色”也应该是Brushes.Red ,您可以在xaml端使用string,因为它可以将字符串转换为类型,而在代码背后,则需要设置类型。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM