繁体   English   中英

wpf Datagrid单元格格式化

[英]wpf Datagrid Cell Formatting

作为WPF的新手,我正在尝试格式化DataGrid单元格。 我找到了以下代码并正在使用它,但是,它没有任何作用。

在此示例中,我要做的就是格式化其中有日期的列。 有人能指出我正确的方向吗???

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

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

提前致谢。

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

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

您的“粗体”应该是FontWeights.Bold“红色”也应该是Brushes.Red ,您可以在xaml端使用string,因为它可以将字符串转换为类型,而在代码背后,则需要设置类型。

下面的代码按预期为我工作(但如果需要将其重新用于其他单元格,则可以提取样式)

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