Search code examples
wpfxamlbuttondata-bindingdatatemplate

Binding a button nested in DataTemplate


I need to bind a button's command inside a datatemplate like below:

                      <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <Button Content="-" Cursor="Hand" Width="50"
                                            Background="Red" x:Name="removeButton"
                                            Command="{Binding Remove}" />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>

Unfortunately it does not work. How can I bind a command in a button insade a datatemplate?

I found that thread in the forum:

Bindings in nested WPF DataTemplates

but the method given by person, who answered this question, does not work as well. I think, that something has changed in WPF since this time, I would you grateful for your help.


Solution

  • If Remove is defined in the view model of the parent ListView, you could bind to it using a RelativeSource:

    Command="{Binding DataContext.Remove,
        RelativeSource={RelativeSource AncestorType=ListView}}"
    

    You could also set the AncestorType to Window or UserControl depending on where the command property is defined and where the DataTemplate is applied.