WPF:按钮模板中图像下的文本

WPF: Text under image in button template

我正在尝试使用堆栈面板将文本放在按钮模板内的图像下方,但它不起作用。只有图像可见,文本不可见。使用模板,我可以将图像作为背景填充所有按钮。见下文:

            <Button Name="btnAdd" Height="36" Width="36" Click="btnAdd_Click" HorizontalAlignment="Center" Margin="10">
                <Button.Template>
                    <ControlTemplate>     
                        <StackPanel Orientation="Vertical">
                           <Image Source="/MyPath/Add.png"/>                               
                           <Label Padding="0">My Button Text</Label>
                        </StackPanel>
                    </ControlTemplate>
                </Button.Template>                    
            </Button>

我怎样才能使我的标签以小字体显示在图像下方的中央?

你有两个问题。您将 ButtonHeightWidth 设置为 36,但文本 "My Button Text" 比 36 宽。如果您 Add.png 比 36 像素高,那么您将没有任何 space 用于显示文本。

这就是为什么我建议设置 Image WidthHeight 而不是 Button WidthHeight

为了在图像下方的中心显示文本,您应该将 LabelHorizontalAlignment 属性 设置为 "Center"。

结果可能是这样的

<Button>
    <Button.Template>
        <ControlTemplate>
            <StackPanel Orientation="Vertical">
                <Image Source="/MyPath/Add.png" 
                       Height="36" 
                       Width="36"/>
                <Label HorizontalAlignment="Center"
                       Content="My Button Text" />
            </StackPanel>
        </ControlTemplate>
    </Button.Template>
</Button>

并以更短的形式

<Button>
    <StackPanel Orientation="Vertical">
        <Image Source="/MyPath/Add.png" 
               Height="36" 
               Width="36"/>
        <Label HorizontalAlignment="Center"
               Content="My Button Text" />
    </StackPanel>
</Button>