所以我有以下数据网格,绑定到一些动态数据:
<DataGrid x:Name="dataGrid" AutoGenerateColumns="False" ColumnHeaderStyle="{StaticResource timmy}">
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"></DataGridTextColumn>
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"></DataGridTextColumn>
<DataGridTemplateColumn Header="Cars">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DataGrid ItemsSource="{Binding Cars}" AutoGenerateColumns="False" Margin="-10,-3,-10,-5" ColumnHeaderStyle="{StaticResource timmy2}">
<DataGrid.Columns>
<DataGridTextColumn Header="Brand" Binding="{Binding Brand}" Width="170"></DataGridTextColumn>
<DataGridTextColumn Header="Model" Binding="{Binding Model}" Width="170"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
这个原型运行良好,但我现在需要在运行时填充内部DataGrid的列。我知道我可以通过编程方式设置DataGridTemplateColumn:
DataGridTemplateColumn gridColumn = new DataGridTemplateColumn();
gridColumn.Header = key;
gridColumn.Width = DataGridLength.Auto;
gridColumn.MinWidth = 160.0;
var dataGridFactory = new FrameworkElementFactory(typeof(DataGrid));
gridColumn.CellTemplate = new DataTemplate() { VisualTree = dataGridFactory };
this.resultsDataGrid.Columns.Add(gridColumn);
但是,由于我正在处理工厂,我该如何设置我的列?
答案 0 :(得分:0)
我找到了解决方案。我必须在代码中创建一个自定义XAML字符串,然后使用XamlReader来读取它:
DataGridTemplateColumn gridColumn = new DataGridTemplateColumn();
gridColumn.Header = patientColumnName;
gridColumn.Width = DataGridLength.Auto;
StringBuilder xamlBuilder = new StringBuilder();
xamlBuilder.AppendLine("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">");
xamlBuilder.AppendLine(" <DataGrid ItemsSource = \"{Binding Visits}\" AutoGenerateColumns = \"False\" Margin = \"-10,-3,-10,-5\">");
xamlBuilder.AppendLine(" <DataGrid.Columns>");
// Put whatever here.
xamlBuilder.AppendLine(" </DataGrid.Columns>");
xamlBuilder.AppendLine(" </DataGrid>");
xamlBuilder.AppendLine("</DataTemplate>");
DataTemplate dataTemplate = XamlReader.Parse(xamlBuilder.ToString()) as DataTemplate;
gridColumn.CellTemplate = dataTemplate;