Styling a WPF Button with Image+Text

后端 未结 4 4987
忘了有多久
忘了有多久 2021-02-20 19:04

In my C#/WPF/.NET 4.5 application I have buttons with images that I implemented in the following fashion:

相关标签:
4条回答
  • 2021-02-20 19:21

    Try something like this:

    The Button:

    <Button Style="{StaticResource BigButton}" Content="save">
        <Button.Tag>
            <ImageSource>../GreenLamp.png</ImageSource>
        </Button.Tag>
    </Button>
    

    The Style:

    <Style TargetType="Button" x:Key="BigButton">
        <Setter Property="Cursor" Value="Hand" />
        <Setter Property="Height" Value="80" />
        <Setter Property="Width" Value="80" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="FontWeight" Value="Bold" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border x:Name="border"
                            CornerRadius="5"
                            Background="#FF415360">
                        <StackPanel>
                            <Image Source="{TemplateBinding Tag}" 
                                    VerticalAlignment="Top"
                                    HorizontalAlignment="Center"
                                    Height="50"
                                    Margin="5" />
                            <ContentPresenter x:Name="ButtonContentPresenter"
                                            VerticalAlignment="Center"
                                            HorizontalAlignment="Center">
                        </ContentPresenter>
                        </StackPanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    

    You might have to change the Height/Margin for the Image in the Style to fit your needs.

    0 讨论(0)
  • 2021-02-20 19:26

    I think, it will work if you set Button's ContentTemplate instead of Content.

    <Button Style="{StaticResource BigButton}">
        <Button.ContentTemplate>
            <DataTemplate>
              <StackPanel>
                <Image Source="Resources/icon_cancel.png" />
                <TextBlock>save</TextBlock>
              </StackPanel>
            </DataTemplate>
        </Button.ContentTemplate>
    </Button>
    
    0 讨论(0)
  • 2021-02-20 19:31

    The solution to your problem may be to move your Image and TextBlock styles to the ControlTemplate's Resource section. I'm not sure why, but I believe the styles aren't in scope if they are part of the content presenter's resources.

    0 讨论(0)
  • 2021-02-20 19:36

    Use height property to fix Image height to let say 30(depend on your reqirement) and use HorzontalAllignment to center for textblock It wil work fine

    0 讨论(0)
提交回复
热议问题