2016-01-26 111 views
4

我有一個自定義按鈕的下面的代碼集。但我想改變一個按鈕的背景。需要幫助覆蓋WPF按鈕樣式的背景顏色。

<Style x:Key="myButtonStyle" TargetType="{x:Type Button}"> 
<Setter Property="Foreground" Value="White"/> 
<Setter Property="Template"> 
    <Setter.Value> 
     <ControlTemplate TargetType="{x:Type Button}"> 
      <Grid> 
       <Rectangle x:Name="rectangle" Fill="#FF2F2FEA" Stroke="Black"> 
        <Rectangle.Effect> 
         <DropShadowEffect ShadowDepth="3"/> 
        </Rectangle.Effect> 
       </Rectangle> 
       <ContentPresenter x:Name="contentPresenter" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Bottom" Margin="2.833,0,2.5,1.162" RenderTransformOrigin="0.5,0.5" Width="69.667"/> 
      </Grid> 
     </ControlTemplate> 
    </Setter.Value> 
</Setter> 

下面的代碼是爲了覆蓋的背景顏色,但沒有。我錯過了什麼?由於

<Style x:Key="SpecialButton" TargetType="Button" BasedOn="{StaticResource myButtonStyle}"> 
    <Setter Property="Background" Value="PaleGreen" /> 
    <Setter Property="Height" Value="19.96" /> 
</Style> 

回答

7

添加<Setter Property="Background" Value="#FF2F2FEA" />myButtonStyle。而就在RectangleFill="{TemplateBinding Background}"

<Style x:Key="myButtonStyle" TargetType="{x:Type Button}"> 
    <Setter Property="Foreground" Value="White"/> 
    <Setter Property="Background" Value="#FF2F2FEA" /> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type Button}"> 
       <Grid> 
        <Rectangle x:Name="rectangle" Fill="{TemplateBinding Background}" Stroke="Black"> 
         <Rectangle.Effect> 
          <DropShadowEffect ShadowDepth="3"/> 
         </Rectangle.Effect> 
        </Rectangle> 
        <ContentPresenter x:Name="contentPresenter" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
            RecognizesAccessKey="True" 
            SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
            VerticalAlignment="Bottom" 
            Margin="2.833,0,2.5,1.162" 
            RenderTransformOrigin="0.5,0.5" Width="69.667"/> 
       </Grid> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

在此之後改變Fill,兩個Button S的關係正確顯示。

<StackPanel> 
    <Button Content="BASE" Style="{StaticResource myButtonStyle}"></Button> 

    <Button Content="DERIVED" Style="{StaticResource SpecialButton}"></Button> 
</StackPanel> 

結果:

result

說明:如果您更改ControlTemplate你要 「線式」 它的屬性(如BackgroundForegroundHorizontalContentAlignment等),屬性元素在ControlTemplate。畢竟,你想賦予控制終端用戶修改顏色,對齊方式等功能,而不是隻有一個帶有靜態可視化樹的Control

+1

你打我吧:)),是的,當你重寫按鈕的ControlTemplate時,Button的背景是沒有用的,除非你使用了一個模板綁定到它(y) – Usama

+0

那麼這個伎倆。這XAML的東西肯定有凝灰岩學習曲線。謝謝你的解釋! – JimDel