带图像的WPF按钮样式

时间:2013-05-20 12:49:42

标签: wpf styles

我想为里面有不同图像的按钮创建一个样式。我尝试做以下事情:

<Style TargetType="Button"
       x:Key="PaintButton">
  <Setter Property="Width"
          Value="40"></Setter>
  <Setter Property="Height"
          Value="40"></Setter>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate>
        <Grid>
          <Border CornerRadius="3"
                  BorderThickness="2"
                  BorderBrush="Green">
            <Image Source="{TemplateBinding Button.Content}" />
          </Border>
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

并尝试使用:

<Button Content="images/pen.png"
        HorizontalAlignment="Left"
        Style="{DynamicResource PaintButton}" />

但未显示图像。为什么以及如何正确地做到这一点?

2 个答案:

答案 0 :(得分:3)

“图像”不是另一个图像的正确来源。 使用BitmapImage作为Button的内容或在模板中使用ContentPresenter。

选项1。

    <Button Style="{StaticResource PaintButton}">
        <BitmapImage UriSource="Back_Forward.png"/>
    </Button>

选项2。

<Setter Property="Template">
  <Setter.Value>
    <ControlTemplate>
      <Grid>
        <Border CornerRadius="3"
                BorderThickness="2"
                BorderBrush="Green">
          <ContentPresenter Content="{TemplateBinding Button.Content}" />
        </Border>
      </Grid>
    </ControlTemplate>
  </Setter.Value>
</Setter> 

答案 1 :(得分:2)

请试试这个

<Style TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <StackPanel Orientation="Horizontal">
                        <Grid Height="30" Width="30" Background="{TemplateBinding Background}"/>
                        <TextBlock Text="{TemplateBinding Content}"  TextAlignment="Center" VerticalAlignment="Center"/>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Cursor" Value="Hand"/>
            </Trigger>
        </Style.Triggers>
    </Style>

<Button Name="btnPrintCard" Margin="2" Content="Print Card">
                <Button.Background>
                    <ImageBrush ImageSource="images/ic_print_black_48dp.png"/>
                </Button.Background>
            </Button>