vip1all
vip1all

Reputation: 122

DataGrid CellTemplate, Pass DataContext as Command Parameter

I have a DataGrid which ItemsSource is set to ObservableCollection<ObservablePuls>.

In last column I have a button, and I would like to bind its CommandParameter to ObservablePuls. With this code I get null passed as CommandParameter and this error:

BindingExpression path error: 'DataContext' property not found on 'object' ''ObservablePuls' (HashCode=40133923)'. BindingExpression:Path=DataContext; DataItem='ObservablePuls' (HashCode=40133923); target element is 'Button' (Name=''); target property is 'CommandParameter' (type 'Object')

So here is my question: How do I pass object that is the source of row?

Here is code of DataGrid with button (omitted other columns):

<DataGrid x:Name="PulsesDataGrid"
          Grid.Row="1"
          ItemsSource="{Binding ObservableUser.Pulses}"
          CanUserAddRows="False"
          CanUserSortColumns="True"
          AutoGenerateColumns="False"
          materialDesign:DataGridAssist.CellPadding="13 8 8 8"
          materialDesign:DataGridAssist.ColumnHeaderPadding="8"
          CanUserDeleteRows="False"
          CanUserReorderColumns="True"
          HorizontalAlignment="Stretch">
    <DataGrid.Columns>

        //... Other columns here

        <DataGridTemplateColumn Header="">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Style="{StaticResource MaterialDesignToolButton}"
                            Margin="10 0 0 0"
                            Command="{Binding ElementName=PulsesDataGrid, Path=DataContext.DeleteRowInDataGrid}"
                            CommandParameter="{Binding Path=DataContext}">
                        <materialDesign:PackIcon Kind="DeleteForever" />
                    </Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Binding Command is fine as it is being invoked with a null parameter ;(

Upvotes: 0

Views: 645

Answers (1)

S. Spindler
S. Spindler

Reputation: 546

You can bind the current DataContext in your DataTemplate (wich is the element displayed in the row) to the CommandParameter by using:

CommandParameter="{Binding}"

Upvotes: 1

Related Questions