将CellTemplate应用于绑定到动态DataTable的DataGrid



我的应用程序在运行时构建一个数据表(行和列(,因此列/属性是可变的。现在我把它显示在一个数据网格&尝试设置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中构建它。。。所以我真正需要的是将column参数传递给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;
}

所以我真正需要的是将列参数传递给XAML

恐怕没有"XAML解决方案"可以绑定到生成时名称未知的属性。毕竟XAML是一种标记语言。

因此,您必须以编程方式动态地为每列创建一个DataTemplate,就像您目前在GetDataTemplate方法中所做的那样。不能在XAML中执行类似Text="{Binding [DynamicValue]}"的操作。

您可以引用此论坛,在代码隐藏中创建DataTemplate期间,将底层数据对象动态绑定到控件的属性。

注:我在Syncfusion工作。

最新更新