br0ken.pipe
br0ken.pipe

Reputation: 910

Binding Command withing a DataGridTemplateColumn

I would like to bind a command ("EditOrCreateStudentCommand") to a button within a DataGridTemplateColumn. The DataContext in this case is the StudentViewModel. This is defined in the Grid.

Within the DataTemplate I cannot execute the command (nothing happens). Outside the template I can execute the command without problems. What could be the reason?

<Grid DataContext="{Binding StudentViewModel}">
   <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Students}">
      <DataGrid.Columns>
         <DataGridTextColumn Binding="{Binding Name}" IsReadOnly="True" Width="*" />
         <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
               <DataTemplate>
                  <Button Command="{Binding Path=DataContext.EditOrCreateStudentCommand, RelativeSource={RelativeSource AncestorType=Grid}}"/>
               </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
         </DataGridTemplateColumn>
      </DataGrid.Columns>
   </DataGrid>
</Grid>

I already looked at the other same questions on stackoverflow, but none of them solved this problem.

Upvotes: 0

Views: 124

Answers (1)

itaiy
itaiy

Reputation: 1284

The root cause of your problem is that the DataGrid template contains Grid. That why when you set the relative source, you will get the incorrect Grid. From the visual Tree view in the visual studio:

enter image description here

A possible solution to your problem is to add Name to the grid and refernce it by ElementName in the binding:

<Grid x:Name="StudentGrid" DataContext="{Binding StudentViewModel}">
   <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Students}">
      <DataGrid.Columns>
         <DataGridTextColumn Binding="{Binding Name}" IsReadOnly="True" Width="*" />
         <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
               <DataTemplate>
                  <Button Command="{Binding Path=DataContext.EditOrCreateStudentCommand, ElementName=StudentGrid}"/>
               </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
         </DataGridTemplateColumn>
      </DataGrid.Columns>
   </DataGrid>
</Grid>

Upvotes: 1

Related Questions