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.
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)...
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 .
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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.