2013-08-22 42 views
0

我有一個DataGrid,其ItemsSource被設置爲一個DataTable。 DataTable具有DateTime類型的列,並且如果特定單元格中的日期爲特定值,我想顯示信息文本(即「N/A」)。轉換DataGrid單元格內容

我的第一個想法是以某種方式將細胞內容綁定到自身,並使用一個轉換器,但我似乎無法使其正常工作,並且似乎應該有更好的方法。

此外,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,但我猜的問題在於某處的結合,因爲DateTimeToStringConverter顯示DataGrid中時,實際上從未被調用。

回答

1

起初,你添加變量名稱爲二傳手的二傳手集合,但你是名mySetter定義變量。這可能是一個原因,爲什麼你的轉換器沒有被實際調用。

此外,您的問題的解決方案會更復雜一點。 實際上,Convert得到一個包含整行數據的RowDataView類型的值。轉換器中沒有關於實際綁定的Column或Cell的信息。

更好的是跳過AutoGenerateColumns並以編程方式生成它們。 這裏是例子:

myDataGrid.ItemsSource = myDataTable.DefaultView; 
myDataGrid.AutoGenerateColumns = false; 

foreach (DataColumn column in myDataTable.Columns) 
{ 
    Binding binding = new Binding(column.ColumnName) 
     { 
      Converter = new DateTimeToStringConverter() 
     }; 
    DataGridColumn gridColumn = new DataGridTextColumn 
     { 
      SortMemberPath = column.ColumnName, 
      Header = column.ColumnName, 
      Binding = binding 
     }; 
    myDataGrid.Columns.Add(gridColumn); 
} 

當然,對於性能會更好只在一個DateTime列使用轉換器。

相關問題