且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

继承的WPF自定义控件不会继承父命令

更新时间:2022-01-08 07:51:02

将控制模板内 Button 的命令绑定到模板化父级.

Bind the command of the Button inside of your control template to the templated parent.

<ControlTemplate TargetType="{x:Type local:IconButton}">
   <Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
           Command="{TemplateBinding Command}"
           CommandParameter="{TemplateBinding CommandParameter}"
           CommandTarget="{TemplateBinding CommandTarget}">
      <!-- ...other code. -->
   </Button>
</ControlTemplate>

但是它应该可以工作,因为继承仍然是一个按钮.

But it should work, as per inheritance it still is a button..

不.控件模板内部的 Button 不会神奇地绑定到其模板化父级的相应属性,无论它是从 Button 还是任何其他控件派生而来的.对于其他依赖项属性(例如 CommandParameter ),也必须这样做.

No. The Button inside of your control template does not magically bind to the corresponding properties of its templated parent, regardless if it is derived from Button or any other control. You will have to do so for other dependency properties like the CommandParameter as well.

另请注意, Binding 标记扩展名.因此,当 TemplateBinding 不起作用时,例如在双向绑定方案中,您可以像这样使用 TemplatedParent :

Please also note that TemplateBinding is an optimized binding that does not have all capabilities of the more powerful Binding markup extension. Consequently, when TemplateBinding does not work, e.g. in two-way binding scenarios, you can use TemplatedParent like this:

{Binding RelativeSource={RelativeSource TemplatedParent}, Path=MyDependencyProperty}

有关更多信息,您可以参考

For more information, you can refer to the TemplateBinding documentation.