我的应用程序在运行时构建了一个数据表(行和列),因此列/属性是可变的。现在我在数据网格中显示它并尝试设置 CellTemplate 并没有成功绑定每个单元格值。它在应用 CellTemplates 之前正确显示值...
这是我使用 & 指定单元格样式构建数据网格的代码:
private void BuildDataGridColumnsFromDataTable(DataTable dT)
{
foreach (DataColumn dTColumn in dT.Columns)
{
var binding = new System.Windows.Data.Binding(dTColumn.ToString());
DataTemplate dt = null;
if (dTColumn.ColumnName == "Country")
{
GridTextColumn textColumn = new GridTextColumn();
textColumn.MappingName = "Country";
textColumn.Width = 100;
MatrixDataGrid.Columns.Add(textColumn);
}
else
{
dt = (DataTemplate)Resources["NameTemplate"];
GridTextColumn textColumn = new GridTextColumn();
textColumn.MappingName = dTColumn.ColumnName;
textColumn.CellTemplate = dt;
MatrixDataGrid.Columns.Add(textColumn);
}
}
}
和一个单元格样式。我一直无法检索每个数据表单元格值。因此,例如在这里,我只需获取原始数据表单元格值并在每个数据网格文本块中绑定/显示它们。
<DataTemplate x:Key="NameTemplate">
<TextBlock Name="NameTextBlock" DataContext="{Binding RelativeSource={RelativeSource AncestorType=DataGridCell}, Converter={StaticResource drvc}}"
Text="{Binding}" Background="LightGreen"/>
</DataTemplate>
- - 编辑 - -
我可以通过在代码隐藏中构建数据模板并传递运行时创建的列(属性)来实现它,如下所示:
textColumn.CellTemplate = GetDataTemplate(dTColumn.ColumnName);
不过,我更喜欢在 XAML 中构建它......所以我真正需要的是将列参数传递给 XAML。任何如何最好地实现这一目标的想法将不胜感激!
private static DataTemplate GetDataTemplate(string col)
{
DataTemplate template = new DataTemplate();
FrameworkElementFactory txtBox = new FrameworkElementFactory(typeof(TextBox));
txtBox.SetValue(TextBox.TextAlignmentProperty, TextAlignment.Center);
txtBox.SetValue(TextBox.BackgroundProperty, (Brush)(new BrushConverter()).ConvertFromString("#9EB11C"));
template.VisualTree = txtBox;
System.Windows.Data.Binding bind = new System.Windows.Data.Binding
{
Path = new PropertyPath(col), //Provides the column (property) at runtime.
Mode = BindingMode.TwoWay
};
// Third: set the binding in the text box
txtBox.SetBinding(TextBox.TextProperty, bind);
return template;
}