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

时间:2017-03-30 15:25:29

标签: wpf xaml silverlight

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

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

1 个答案:

答案 0 :(得分:2)

试试这个:

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

这适用于WPF。在Silverlight中,我担心你不能这样做。

相关问题