需求:我们在写控件样式的时候有时候需要在样式中添加一个按钮,例如ListBox在ListBoxItem中的ControlTemplate里面添加一个按钮,按钮的Conmmand想要和ViewModel里的方法Binding。
实现:
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template" >
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Button Name="TestButton" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=DataContext.TestCommand}" CommandParameter="{Binding ElementName=TestButton}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
总结:其中里面的 TestCommand 就是ViewModel中你想要绑定的Command,CommandParameter决定是否需要传参数。