Xaml 从父级继承的样式资源

Xaml 从父级继承的样式资源,xaml,Xaml,我在另一个stackpanel中嵌套了两个堆栈面板,嵌套的堆栈面板都有需要相同大小的图像,所以我使用了样式资源。但这意味着复制每个堆栈面板中的样式资源。如图所示 <StackPanel Orientation="Vertical"> <StackPanel Orientation="Horiztonal"> <StackPanel.Resources> <Style TargetType="Image"&g

我在另一个stackpanel中嵌套了两个堆栈面板,嵌套的堆栈面板都有需要相同大小的图像,所以我使用了样式资源。但这意味着复制每个堆栈面板中的样式资源。如图所示

<StackPanel Orientation="Vertical">
    <StackPanel Orientation="Horiztonal">
        <StackPanel.Resources>
            <Style TargetType="Image">
                <Setter Property="Width" Value="20"/>
            </Style>
        </StackPanel.Resources>
        <Image />
        <Image />
        <Image />
        <Image />
    </StackPanel>

    <StackPanel Orientation="Horiztonal">
        <StackPanel.Resources>
            <Style TargetType="Image">
                <Setter Property="Width" Value="20"/>
            </Style>
        </StackPanel.Resources>
        <Image />
        <Image />
        <Image />
        <Image />
    </StackPanel>
</StackPanel>


有没有办法在我周围的stackpanel上设置此样式并让子级继承该样式,或者我会考虑制作一个样式模板(如图所示;)并将其单独应用于我的图像?

我不建议使用“上一个样式”作为基础继承样式。相反,我会将该样式显式定义为静态资源的基础样式,然后将该样式应用于需要该样式(或继承该样式)的任何控件。 例如:

在用户控件级别,让我们定义基本样式

<UserControl>
   <UserControl.Resources>
      <!--Define StackPanel Style with a key as the base-->
      <Style x:Key="ImageStyle" TargetType="{x:Type Image}">
          <Setter .... />
      </Style>
      <!-- To apply the style above, you need to explicitly set the style using Style="{StaticResource ImageStyle}"-->
   </UserControl.Resources>
</UserControl>

在主体中,我们可以将样式应用于特定控件,但在本例中,我们希望应用于OuterStackPanel内的所有图像,因此:

<StackPanel x:Name="OuterStackPanel">
   <StackPanel.Resources>
      <!-- Without specifying the key, this will apply the style to all Images inside this StackPanel including NestedStackPanels -->
      <!-- Also, with BasedOn, this will inherit the style from ImageStyle defined above -->
      <Style TargetType="{x:Type Image}" BasedOn="{StaticResource ImageStyle}">
         <Setter .../> <!-- In Case if you want to add another setter, for ex: Width=20. Or don't add any other Setter to have the original style-->
      </Style>
   </StackPanel.Resources>
   <StackPanel x:Name="NestedStackPanel1">
      <Image />
      <Image />
      <Image />
      <Image />
   </StackPanel>
   <StackPanel x:Name="NestedStackPanel2">
      <Image />
      <Image />
      <Image />
      <Image />
   </StackPanel>
</StackPanel>


如果每个nestedStackPanel需要不同的样式,可以将样式移到nestedStackPanel内部。

谢谢,我想解决方案应该是这样的。