這讓我感到瘋狂。我在代碼中創建一個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]