Binding a WPF Button CommandParameter to the Button itself in DataTemplate

為{幸葍}努か 提交于 2020-01-29 06:38:05

问题


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?


回答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.




回答2:


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

<Button x:Name="MyButton" Command="{Binding Command}" CommandParameter={Binding ElementName=MyButton ... /> 


来源:https://stackoverflow.com/questions/12413985/binding-a-wpf-button-commandparameter-to-the-button-itself-in-datatemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!