Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a WPF Button CommandParameter to the Button itself in DataTemplate

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?

like image 549
Jippers Avatar asked Sep 13 '12 20:09

Jippers


People also ask

How do I bind an item to a datatemplate in WFP?

WFP: Binding an Item inside ItemsControl's DataTemplate to the Property on Page DataContext. In most scenarios we bind the ItemControl's ItemsSource to the collection of Data Model item. Then we configure our DataTemplate Binding to the properties inside Data Model item.

What does the commandparameter get from the button's DataContext?

This might be a little easier to understand if you know, that {Binding} is actually the same as {Binding DataContext,RelativeSource= {RelativeSource Self}}. So in your case CommandParameter gets the value of the current DataContext of the Button.

How to bind XAML commands to button controls in MVVM?

Suppose we have three buttons and each Button has its own command in the ViewModel. Then it can be done by adding three different ICommand properties in the ViewModel and bind those commands inside the XAML to the respective Button controls. This is the very straight forward approach in MVVM model.

How to bind button content and buttontag in XAML?

Bind ButtonContent and ButtonTag property of CategoryItem to the Button 's Content and Tag properties, respectively in XAML. Here, we are using Tag property from Button class and this will help us to identify which Button is pressed and Content is use for display string on Button.


2 Answers

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

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

like image 196
Miklós Balogh Avatar answered Oct 13 '22 06:10

Miklós Balogh


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

<Button x:Name="MyButton" Command="{Binding Command}" CommandParameter={Binding ElementName=MyButton ... /> 
like image 38
King Chan Avatar answered Oct 13 '22 06:10

King Chan