如何将命令参数绑定到self?
我试着这样:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Button Content="G"
Background="Green"
Foreground="White"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},
Path=DataContext.LabelGoodCommand}"
CommandParameter="{Binding /}"
Width="20" Height="20" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
但这不起作用。 在绑定到ObservableCollection的viewmodel列表框项中。
答案 0 :(得分:0)
CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}"
通过这个你可以获得Control并在你的Execute方法中,像这样使用,
if(pram is Button)
{
var model = ((Button)pram).DataContext;
}
你可以在这里获得模型。
或强>
<Button Content="G"
Background="Green"
Foreground="White"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},
Path=DataContext.LabelGoodCommand}"
CommandParameter="{TemplateBinding DataContext}"
Width="20" Height="20" />
或强>
<Button Content="G"
Background="Green"
Foreground="White"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},
Path=DataContext.LabelGoodCommand}"
CommandParameter="{Binding DataContext,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}"
Width="20" Height="20" />
答案 1 :(得分:-1)
如果用“self”表示按钮,你可以这样做:
CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}"
如果您想要当前的DataContext
,请不要指定路径:
CommandParameter="{Binding}"