WPF中的嵌套样式

时间:2015-05-12 10:10:30

标签: c# wpf styles

我想将Style嵌套在WPF中。

我有一个资源字典:

<Style x:Key="BottomButtonBar" TargetType="{x:Type Grid}">
  <Style TargetType="{x:Type Button}">
        <Setter Property="Margin" Value="10,2" />
        <Setter Property="Width" Value="90" />
    </Style>

    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="HorizontalAlignment" Value="Center" />
        <Setter Property="VerticalAlignment" Value="Center" />
        <Setter Property="Margin" Value="2,0"/>
    </Style>
</Style>

我想要的是:如果我应用风格&#34; BottomButtonBar&#34;在网格上,此网格内的按钮已定义MarginWidth我已定义,此网格中的TextBlock也相同。

怎么做?

2 个答案:

答案 0 :(得分:3)

我终于找到了以下解决方案:

<Style x:Key="BottomButtonBar" TargetType="{x:Type Grid}">
    <Style.Resources>

        <Style TargetType="{x:Type Button}">
            <Setter Property="Margin" Value="10,2" />
            <Setter Property="Width" Value="90" />
        </Style>

        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="Margin" Value="2,0"/>
        </Style>
    </Style.Resources>
</Style>

在XAML中:

    <Grid DockPanel.Dock="Bottom" Style="{DynamicResource BottomButtonBar}">

答案 1 :(得分:0)

如果要为Grid中的元素添加样式,可以隐式设置样式并将它们添加到Grid的资源中以限制其范围:

<Grid>
  <Grid.Resources>
    <Style TargetType="{x:Type Button}">
      <Setter Property="Margin" Value="10,2" />
      <Setter Property="Width" Value="90" />
    </Style>

    <Style TargetType="{x:Type TextBlock}">
      <Setter Property="HorizontalAlignment" Value="Center" />
      <Setter Property="VerticalAlignment" Value="Center" />
      <Setter Property="Margin" Value="2,0"/>
    </Style>
  <Grid.Resources />

  <Button ... />
</Grid>