从父级继承的样式资源

时间:2018-04-23 08:24:22

标签: xaml

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

<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>

有没有办法在我周围的堆栈面板上设置这个样式并让孩子继承该样式,或者我是否正在制作样式模板(如图所示; https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/styling-and-templating)并将其单独应用于我的图像?

1 个答案:

答案 0 :(得分:1)

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

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

<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>

在正文中,我们可以将样式应用于特定的Control,但在我们的例子中,我们想要应用于OuterStackPanel内的所有Images,因此:

<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中移动样式。