How to pass DataGridColumn as a command parameter ? (WPF)

41 views Asked by At

My DataGrid has some columns with the same template.

<DataTemplate x:Key="ButtonCellTemplate">
    <Button Content="TestButton"
            Command="{Binding TestCommand}"
            CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, 
                              AncestorType=DataGridColumn}}"
            />
</DataTemplate>

It doesn't work and I know why.

How can I pass DataGridColumn (or DataGridColumnHeader) as a command parameter ? In other words, I need to know in ViewModel from which column the command is called.

1

There are 1 answers

0
EldHasp On

If we do not touch upon the issue that it is fundamentally conceptually wrong to receive such information in the ViewModel, then this can be implemented, but in a slightly different way.

You have a misunderstanding of the DataGrid visual tree. It is the successor of ItemsControl. Therefore, each row is intended to display an element of the source collection. Cells are placed in a row to represent one or another element of the row - usually one of the properties of that element. Columns as such don't really exist. These are simply containers from which cells receive the data they need. Therefore, the column is not an ancestor for the cell, much less for its contents.

But the cell has a property for communication with the column in which it is located. You can use it.

<DataTemplate x:Key="ButtonCellTemplate">
    <Button Content="TestButton"
            Command="{Binding TestCommand}"
            CommandParameter="{Binding Column,
                                       Mode=OneWay,
                                       RelativeSource={RelativeSource FindAncestor,
                                                                      AncestorType={x:Type DataGridCell}}}"/>
</DataTemplate>