2011-02-10 71 views
0

我定義了一個自定義的WPF樣式。我想要網格中的任何按鈕都是紅色的。但如果我定義這種風格,整個網格是紅色!爲什麼?我明確定義了Button.Background。爲什麼WPF樣式應用於父控件?

<Window x:Class="WpfApplication2.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 

    <Window.Resources> 
     <Style x:Key="MyStyle"> 
      <Setter Property="Button.Background" Value="Red" /> <!-- Only inner buttons --> 
     </Style>    
    </Window.Resources> 

    <Grid Style="{StaticResource MyStyle}"> 
     <Button Content="Go" Margin="29,36,385,239" /> 
    </Grid> 
</Window> 

回答

0

您不能將TargetType設置爲按鈕,以便此樣式僅應用於按鈕?

<Style x:Key="MyStyle" TargetType="Button"> 
    <Setter Property="Background" Value="Red" /> 
</Style> 
+0

不,因爲樣式必須應用於網格。並應包含不同內部控件的所有不同樣式 – Robert 2011-02-10 13:16:07

1

要實現你以後,我認爲你得給內Style.Resources限定內部Style秒。這將使所有Button S IN的Grid拿起「內部」 Style,除非它們顯式地使用其他Style

<Window.Resources> 
    <Style x:Key="MyStyle"> 
     <Style.Resources> 
      <!-- Only inner buttons --> 
      <Style TargetType="Button"> 
       <Setter Property="Background" Value="Red" /> 
      </Style> 
     </Style.Resources> 
    </Style> 
</Window.Resources> 
<Grid Style="{StaticResource MyStyle}"> 
    <Button Content="Go" Margin="29,36,385,239" /> 
</Grid> 

由於Button.Background不是附加屬性(例如不同TextBlock.Foreground),該Background韓元不適用於Grid中的Button

但至於「爲什麼Grid拿起Background」我無法告訴你。這對我來說似乎是一個錯誤。 背景ButtonControl背景繼承了Grid所以就我所看到的,該值不應由Grid使用,但我可能失去了一些東西

也從Panel繼承如果您嘗試直接設置Button.BackgroundGrid

錯誤MC3015你會得到以下錯誤:附加屬性 「Button.Background」未在 「網格」中定義或它的基類之一。

0

不幸的是,風格不像那樣工作。如果你有一個已知的孩子集合,你可以用類似的信息(醜陋的)作弊:

<Setter Property="{Binding RelativeSource={RelativeSource Self} Path=Children[0].Background}" Value="Red" /> 

當然,如果你知道孩子們指數這只是工作,而且是相當脆弱的。我不確定它是否適用於你的情況b/c你說你必須將樣式應用於網格,所以我猜測網格內容正在動態生成。

相關問題