mahboub_mo
mahboub_mo

Reputation: 3038

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!

Upvotes: 1

Views: 2773

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81253

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>

Upvotes: 2

kmatyaszek
kmatyaszek

Reputation: 19296

Instead of use DataGrid you can use ListView with view GridView.

<DataGridTemplateColumn Header="Complex Data">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>                    
                        <ListView ItemsSource="{Binding ProjectCollection}">
                            <ListView.View>
                                <GridView>
                                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
                                    <GridViewColumn Header="Date" DisplayMemberBinding="{Binding Date}" />
                                </GridView>
                            </ListView.View>
                        </ListView>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

Upvotes: 1

Related Questions