【发布时间】:2013-08-25 16:08:51
【问题描述】:
我有一个 DataGrid,它的 ItemsSource 设置为 DataTable。 DataTable 有一个 DateTime 类型的列,如果特定单元格中的日期是某个值,我想显示信息文本(即“N/A”)。
我的第一个想法是以某种方式将单元格内容绑定到自身,并使用转换器,但我似乎无法让它正常工作,而且似乎应该有更好的方法。
另外,DataGrid 和 DataTable 都是动态生成的,所以必须在后面的代码中完成。
这是我最初尝试的代码:
// Create a new DataGridCellStyle
Style myStyle = new Style();
myStyle.TargetType = typeof(DataGridCell);
// Create the binding
Binding myBinding = new Binding();
myBinding.RelativeSource = RelativeSource.Self;
myBinding.Converter = new DateTimeToStringConverter();
// Add the Content setter
Setter mySetter = new Setter();
mySetter.Property = ContentProperty;
mySetter.Value = myBinding;
myStyle.Setters.Add(setter);
// Set the Style and ItemsSource
myDataGrid.CellStyle = myStyle ;
myDataGrid.ItemsSource = myDataTable.DefaultView;
DateTimeToStringConverter 确实实现了 IValueConverter,但我猜问题出在绑定的某个地方,因为在显示 DataGrid 时实际上从未调用过 DateTimeToStringConverter。
【问题讨论】:
标签: wpf data-binding datagrid datatable converter