使用控制模板作为按钮模板WPF时不显示按钮内容

时间:2014-11-14 17:25:31

标签: c# wpf xaml button controltemplate

所以我在wpf中创建了一个圆形按钮,如下所示:

<Button Grid.Column="3" Width="25" Height="25" Content="X" Margin="10,5,5,5" Foreground="Red" VerticalAlignment="Center" HorizontalAlignment="Center">
    <Button.Template>
        <ControlTemplate>
             <Grid>
                  <Ellipse Name="Ellipse" Fill="{TemplateBinding Background}"/>
             </Grid>
        </ControlTemplate>
    </Button.Template>
</Button>

但它显示的按钮是:

enter image description here

为什么红色X没有出现在按钮的中央?是否可以更改我的xaml,以便显示红色X. (ps。灰色背景是因为我资源中的按钮样式)

1 个答案:

答案 0 :(得分:4)

这是因为Template中没有任何内容可以显示Content。为此,您需要使用ContentPresenter

<Button Grid.Column="3" Width="25" Height="25" Content="X" Margin="10,5,5,5" Foreground="Red" VerticalAlignment="Center" HorizontalAlignment="Center">
    <Button.Template>
        <ControlTemplate TargetType="{x:Type Button}">
            <Grid>
                <Ellipse Name="Ellipse" Fill="{TemplateBinding Background}"/>
                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </Grid>
        </ControlTemplate>
    </Button.Template>
</Button>

您还需要将TargetType="{x:Type Button}"添加到ControlTemplate

相关问题