如何将样式与现有资源字典合并?

时间:2014-05-13 08:47:44

标签: wpf dictionary merge resources

我有这个资源字典:

<Application.Resources>        
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary x:Name="defaultStyles" Source="/ReuxablesLegacy;component/edge.xaml" />
            </ResourceDictionary.MergedDictionaries>

        </ResourceDictionary>
    </Application.Resources>

当我定义下面的样式时,它们会覆盖资源字典中的皮肤而我不想要它,我想&#34;合并&#34;或者&#34;继承&#34;从上面:

 <Grid.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Margin" Value="0,0,0,10" />
            <Setter Property="Width" Value="200" />
        </Style>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="Margin" Value="0,0,0,10" />
            <Setter Property="Width" Value="200" />
        </Style>
        <Style TargetType="{x:Type  DatePicker}" >
            <Setter Property="Margin" Value="0,0,0,10" />
            <Setter Property="Width" Value="200" />
        </Style>
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
</Grid>

我怎么可能使用BasedOn属性或其他东西来实现这个目标?

1 个答案:

答案 0 :(得分:1)

如果您的默认样式资源字典包含这样的条目......

<!--A Style that affects all TextBlocks-->
<Style TargetType="TextBlock">
  <Setter Property="HorizontalAlignment" Value="Center" />
  <Setter Property="FontFamily" Value="Comic Sans MS"/>
  <Setter Property="FontSize" Value="14"/>
</Style>

...然后你可以实现这样的......

<!--A Style that extends the previous TextBlock Style-->
<!--This is a "named style" with an x:Key of TitleText-->
<Style BasedOn="{StaticResource {x:Type TextBlock}}"
       TargetType="TextBlock"
       x:Key="TitleText">
  <Setter Property="FontSize" Value="26"/>
  <Setter Property="Foreground">
  <Setter.Value>
      <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
        <LinearGradientBrush.GradientStops>
          <GradientStop Offset="0.0" Color="#90DDDD" />
          <GradientStop Offset="1.0" Color="#5BFFFF" />
        </LinearGradientBrush.GradientStops>
      </LinearGradientBrush>
    </Setter.Value>
  </Setter>
</Style>

这种方法将提供您所追求的继承效果。

MSDN参考位于http://msdn.microsoft.com/en-us/library/system.windows.style.basedon(v=vs.110).aspx