[英]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.