Binding a WPF Button CommandParameter to the Button itself in DataTemplate

33,102

Solution 1

<Button Command="{Binding Command}" 
        CommandParameter="{Binding RelativeSource={RelativeSource Self}}" />

Your Command property should be the generic version of the RelayCommand: RelayCommand<object> for instance.

Solution 2

Answer like Miklós Balogh said, or you can:

<Button x:Name="MyButton" Command="{Binding Command}" CommandParameter={Binding ElementName=MyButton ... /> 
Share:
33,102
Jippers
Author by

Jippers

loves long walks on the beach, and the smell of thai food.

Updated on January 12, 2021

Comments

  • Jippers
    Jippers over 3 years

    I have a DataTemplate that represents AppBar buttons that I declare through a collection of custom AppBarCommand objects.

      public AppBarCommand(RelayCommand command, string buttonstyle)
      {
         Command = command;
         ButtonStyle = buttonstyle;
      }
    
    <DataTemplate>
       <Button Command="{Binding Command}"
               Style="{Binding ButtonStyle, Converter={StaticResource StringNameToStyleConverter}}"/>
    </DataTemplate>
    

    I would like to add a CommandParameter binding, but the parameter has to be the Button itself. This is so I can set the PlacementTarget of a Callisto flyout. Is this possible?

    • Jay
      Jay almost 12 years
      Probably easier to handle the Button's Click event. The first argument you receive in your handler will be the Button.