当我';我在WPF中使用模板?

当我';我在WPF中使用模板?,wpf,xaml,button,command,controltemplate,Wpf,Xaml,Button,Command,Controltemplate,我有一个按钮模板来定义编辑按钮的外观: <ControlTemplate x:Key="EditButton" TargetType="{x:Type Button}"> <Button Style="{StaticResource GrayOutButtonStyle}" > <Image x:Name="editImage" Source="{StaticResource EditIcon}" /> </Butto

我有一个
按钮
模板来定义编辑按钮的外观:

<ControlTemplate x:Key="EditButton" TargetType="{x:Type Button}">
     <Button Style="{StaticResource GrayOutButtonStyle}" >
        <Image x:Name="editImage" Source="{StaticResource EditIcon}" />
     </Button>
</ControlTemplate>
我的语法有什么问题


(注意:如果我从这个按钮中删除模板,那么
命令就会起作用,所以这是关于使用一个模板的问题,它会把事情搞砸。)

为什么您的
按钮
模板包含另一个
按钮
?这毫无意义,如果您的模板被隐式应用,则会出现堆栈溢出。它应该是
图像
,在这种情况下,您的命令应该可以工作

需要说明的是,您有一个外部的
按钮
,它正确地应用了
ICommand
。但是,它被渲染为另一个
按钮
,里面有一个
图像
。因此,当您单击
图像
时,实际上是在单击内部的
按钮
,该按钮没有与其关联的
ICommand
。外部按钮从未“看到”单击,因此它从未执行命令

您唯一的其他选择(我不推荐,但应该可以)是将内部按钮绑定到外部按钮上的属性:

<ControlTemplate ...>
    <Button Command="{TemplateBinding Command}" CommandParameter="{Binding CommandParameter}" ...>
        <Image .../>
    </Button>
</ControlTemplate>

引用该命令的另一个选项是相对绑定,如下所示:

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="Button">
            <Button Command="{Binding Path=Command, RelativeSource={RelativeSource AncestorType=Button}}">
                <Image... />
            </Button>
        </ControlTemplate>
    </Setter.Value>
</Setter>


因为如果我从模板中删除按钮,那么我只会得到一个图像,它不会显示在按钮外观内部。我希望我的按钮的外观是一个按钮与该图像,并适用于GrayOutattonStyle。因为模板是键控的,所以我认为它不会递归应用——只有在显式声明template={Static Resource EditButton}时才会应用它。这不正确吗?它在模板中确实起作用(必须修改CommandParamater以仅绑定):但是如果这不是模板化一个看起来像带有图像的按钮的正确方法,我仍然希望理解这一点。谢谢如果您只需要在按钮中添加一个图像,“正确的方法”是根本不使用模板,只需声明一个
按钮
,并将
图像
作为其内容。否则,最好从复制现有的
按钮
模板并对其进行修改开始。混合是最好的工具。XAMLPadX可能就足够了。我需要的不是按钮的全部,我在几个地方都需要它。@Abby:DataTemplate可能就足够了。如果你不事先提供所有必要的信息,就很难回答你的问题;)
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="Button">
            <Button Command="{Binding Path=Command, RelativeSource={RelativeSource AncestorType=Button}}">
                <Image... />
            </Button>
        </ControlTemplate>
    </Setter.Value>
</Setter>