2013-10-01 141 views
1

我有一個關於xaml wpf中的樣式的問題。WPF資源覆蓋

我有一個應該適用於所有對象的默認樣式。但對於其中一些人,我想設置第二種風格來覆蓋一些屬性。

現在,如果我給我的第二個樣式一個x:key =「style2」並將其設置爲樣式,我的第一個默認樣式不適用,但默認WPF樣式是。我不能/不想改變我的第一個默認樣式

我該如何解決這個行爲?

回答

6

爲了確保您的默認樣式仍然適用,您可以添加

BasedOn={StaticResource ResourceKey={x:Type ControlType}} 

哪裏ControlType是默認樣式應用到對象的類型。

下面是一個例子:

enter image description here

<Window x:Class="StyleOverrides.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 TargetType="{x:Type TextBlock}"> 
      <Setter Property="FontFamily" Value="Comic Sans MS" /> 
     </Style> 
     <Style x:Key="Specialization" 
       TargetType="{x:Type TextBlock}" 
       BasedOn="{StaticResource ResourceKey={x:Type TextBlock}}" 
     > 
      <Setter Property="FontStyle" Value="Italic" /> 
      <Setter Property="Foreground" Value="Blue" /> 
     </Style> 
    </Window.Resources> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="*" /> 
      <RowDefinition Height="*" /> 
     </Grid.RowDefinitions> 
     <Viewbox Grid.Row="0" > 
      <TextBlock>This uses the default style</TextBlock></Viewbox> 
     <Viewbox Grid.Row="1"> 
      <TextBlock Style="{StaticResource Specialization}"> 
       This is the specialization 
      </TextBlock> 
     </Viewbox> 
    </Grid> 
</Window>