XAML如何在Style中设置控件资源字典?

How to set a control resource dictionary in a Style in XAML?

我在 Silverlight 中有一个带有一些边框的 UI,并且在该边框内有一个 TextBlock。边界外会有其他 TextBlock。

<Border>
    <TextBlock>This text should be centered</TextBlock>
</Border>

<Border>
    <TextBlock>This one too</TextBlock>
</Border>

<TextBlock>this one shouldn't</TextBlock>

我想要实现的是在边框内设置所有 TextBlock 的格式,而不必在每个 TextBlock 中设置样式。如果它是 CSS ,它将是这样的: .border .textBlock { (...) }

我知道我可以在边框范围内设置样式:

<Border>
    <Border.Resources>
        <Style TargetType="TextBlock" BasedOn="{StaticResource DefaultTextBlockStyle}">
            <Setter Property="HorizontalAlignment" Value="Center"></Setter>    
        </Style>
    </Border.Resources>
    <TextBlock>Centered Text</TextBlock>
</Border>

但我仍然需要将此设置到我页面中的每个边框。所以现在我提出一个问题,我可以设置一种样式,以便设置一次以影响所有边框吗?我尝试了下面的代码,但它没有用。它没有给我任何错误,但也没有影响 TextBlock 格式。

<Style TargetType="Border">
    <Setter Property="Resources">
        <Setter.Value>
            <ResourceDictionary>
                <Style TargetType="TextBlock">
                    <Setter Property="HorizontalAlignment" Value="Center" />  
                </Style>
            </ResourceDictionary>
        </Setter.Value>
    </Setter>
</Style>     

试试这个:

<Style TargetType="Border">
    <Style.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="HorizontalAlignment" Value="Center" />
        </Style>
    </Style.Resources>
</Style>

这适用于 WPF。不过在 Silverlight 中恐怕你不能这样做。