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?
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.
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.
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.
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.
<Button Command="{Binding Command}"
CommandParameter="{Binding RelativeSource={RelativeSource Self}}" />
Your Command property should be the generic version of the RelayCommand
: RelayCommand<object>
for instance.
Answer like Miklós Balogh said, or you can:
<Button x:Name="MyButton" Command="{Binding Command}" CommandParameter={Binding ElementName=MyButton ... />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With