2010-07-30 153 views
4

這讓我感到瘋狂。我在代碼中創建一個DataGrid,然後將其綁定到一個數據表。這是動態的,每次創建網格時,行和列都會有所不同。WPF DataGrid綁定到數據表

基本上我遍歷每個列我的數據表和創建的DataGrid列,就像這樣:

private static void CreateDataGridColumns(DataGrid datagrid, Document doc) 
{ 
    if (doc == null) return; //return 

    datagrid.Columns.Clear(); 
    foreach (var item in doc.Keys) 
    { 
     var column = new DataGridTemplateColumn 
     { 
      Header = item, 
      CellTemplateSelector = new CustomRowDataTemplateSelector(), 
     }; 

     datagrid.Columns.Add(column); 
    } 
} 

正如你所看到的,我使用的是自定義數據模板選擇,所以我可以使細胞不同的視在其內容上。

這裏是模板選擇

public class CustomRowDataTemplateSelector : DataTemplateSelector 
{ 
    public override DataTemplate 
     SelectTemplate(object item, DependencyObject container) 
    { 
     FrameworkElement element = container as FrameworkElement; 

     var presenter = container as ContentPresenter; 
     var gridCell = presenter.Parent as DataGridCell; 

     if (element != null && item != null && gridCell != null) 
     { 
      var row = item as DataRow; 

      if (row != null) 
      { 
       var cellObject = row[gridCell.Column.DisplayIndex]; 

       //set template based on cell type 

       if (cellObject is DateTime) 
       { 
        return element.FindResource("dateCell") as DataTemplate; 
       } 

       return element.FindResource("stringCell") as DataTemplate; 
      } 


     } 

     return null; 
    } 
} 

這裏是我的stringCell的DataTemplate

<DataTemplate x:Key="stringCell"> 
    <StackPanel> 
     <TextBlock Style="{StaticResource cellStyle}" 
        Grid.Row="0" Grid.Column="0" 
        Text="{Binding Converter={StaticResource cellConverter}}" /> 
    </StackPanel> 
</DataTemplate> 

的問題是,模板選擇被每單元(如預期),但我不能告訴它是哪個單元格,所以我不知道如何在TextBlock上設置文本。我很樂意做這樣的事情

<DataTemplate x:Key="stringCell"> 
    <StackPanel> 
     <TextBlock Style="{StaticResource cellStyle}" 
        Grid.Row="0" Grid.Column="0" 
        Text="{Binding Path=Row[CellIndex], Converter={StaticResource cellConverter}}" /> 
    </StackPanel> 
</DataTemplate> 

但是沒有什麼可以讓我獲得CellIndex。我該怎麼做類似這個的地方,我可以設置路徑=行[CellIndex]

回答

-1

不知道你試圖實現功能。你可能會在代碼中做到這一點。創建一個具有DisplayValue屬性的更高級別的類CellClass。用日期和字符串的實現。將源代碼綁定到帶有Path = DisplayValue的CellClass。你甚至可以創建List CellClass和綁定到CellClass [0],CellClass [1] ...在知道這個工程,因爲我這樣做,但我不知道它是否提供了您正在尋找的功能。

public abstract class CellClass 
    { 
     public abstract String DispValue { get; } 
    } 
    public class CellClassDate : CellClass 
    { 
     public override String DispValue { get ...; } 
     public DateTime DateValue { get .. set ... } 
    } 
    public class CellClassString : CellClass 
    { 
     public override String DispValue { get ...; } 
     public DateTime StringValue { get .. set ... } 
    } 
0

您可以嘗試在代碼中創建綁定。像這樣的東西應該可以工作

var bind = new Binding(gridCell.Column.Header.ToString()) 
bind.Mode = BindingMode.TwoWay; 
bind.Source = row; 
BindingOperations.SetBinding(YourTextBlock, TextBlock.TextProperty, bind);