C# 将 WPF 按钮 CommandParameter 绑定到 DataTemplate 中的按钮本身
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12413985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding a WPF Button CommandParameter to the Button itself in DataTemplate
提问by Jippers
I have a DataTemplate that represents AppBar buttons that I declare through a collection of custom AppBarCommand objects.
我有一个 DataTemplate 表示我通过自定义 AppBarCommand 对象的集合声明的 AppBar 按钮。
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?
我想添加一个 CommandParameter 绑定,但参数必须是 Button 本身。这样我就可以设置 Callisto 弹出按钮的 PlacementTarget。这可能吗?
采纳答案by Miklós Balogh
<Button Command="{Binding Command}"
CommandParameter="{Binding RelativeSource={RelativeSource Self}}" />
Your Command property should be the generic version of the RelayCommand: RelayCommand<object>for instance.
您的命令属性应该是通用的版本RelayCommand:RelayCommand<object>例如。
回答by King Chan
Answer like Miklós Balogh said, or you can:
像 Miklós Balogh 所说的那样回答,或者您可以:
<Button x:Name="MyButton" Command="{Binding Command}" CommandParameter={Binding ElementName=MyButton ... />

