Search code examples
wpfwpfdatagriddatatemplate

How to add a DataGrid to a DataGridTemplateColumn.CellTemplate


I need to add a DataGrid to a DataGridTempateColumn,so i did this, but it dosen't work correctly,I don't know if i really can add a DataGrid to a DataGridTempateColumn?

<datagrid>
....
<DataGridTemplateColumn.CellTemplate>
     <DataTemplate>
        <DataGrid HeadersVisibility="None" AutoGenerateColumns="False" CanUserAddRows="True"                    ItemsSource="{Binding ProjectCollection}">
                                <DataGridTextColumn Binding="{Binding Spec.Rev}" Width="*"></DataGridTextColumn>
                                <DataGridTextColumn  Binding="{Binding Spec}" Width="*"></DataGridTextColumn>

        </DataGrid>
     </DataTemplate>
 </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
...
</DataGrid>

EDited: while the ProjectCollection is null,we can't see the dataGrid,as you see in row 2 in the picture!


Solution

  • I doubt this will work. You will get the InvalidOperationException - Items collection must be empty before using ItemsSource. since you are setting the ItemsSource for the innner Grid and at the same time you are adding childs to the DataGrid.

    Add the columns to the Columns DP of your dataGrid like this and it will work as you desired -

    <DataGridTemplateColumn.CellTemplate>
         <DataTemplate>
            <DataGrid HeadersVisibility="None" AutoGenerateColumns="False"
                     CanUserAddRows="True" ItemsSource="{Binding ProjectCollection}">
               <DataGrid.Columns>
                   <DataGridTextColumn Binding="{Binding Spec.Rev}" Width="*"/>
                   <DataGridTextColumn  Binding="{Binding Spec}" Width="*"/>
               </DataGrid.Columns>
            </DataGrid>
         </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>