2013-05-20 104 views
0

我想創建一個樣式按鈕與不同的圖像裏面。我嘗試做以下操作:WPF按鈕樣式與圖片

<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

「圖像」不是另一張圖像的正確來源。 將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

請試試這個

<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>