将WPF Button CommandParameter绑定到DataTemplate中的Button本身

Jip*_*ers 11 c# wpf binding datatemplate commandparameter

我有一个DataTemplate代表AppBar按钮,我通过自定义AppBarCommand对象的集合声明.

  public AppBarCommand(RelayCommand command, string buttonstyle)
  {
     Command = command;
     ButtonStyle = buttonstyle;
  }

<DataTemplate>
   <Button Command="{Binding Command}"
           Style="{Binding ButtonStyle, Converter={StaticResource StringNameToStyleConverter}}"/>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

我想添加一个CommandParameter绑定,但参数必须是Button本身.这样我就可以设置Call​​isto弹出窗口的PlacementTarget.这可能吗?

Mik*_*ogh 35

<Button Command="{Binding Command}" 
        CommandParameter="{Binding RelativeSource={RelativeSource Self}}" />
Run Code Online (Sandbox Code Playgroud)

您的Command属性应该是RelayCommand:RelayCommand<object>例如的通用版本.


Kin*_*han 6

像 Mikl\xc3\xb3s Balogh 所说的那样回答,或者你可以:

\n\n
<Button x:Name="MyButton" Command="{Binding Command}" CommandParameter={Binding ElementName=MyButton ... /> \n
Run Code Online (Sandbox Code Playgroud)\n