【问题标题】:How to set a control resource dictionary in a Style in XAML?如何在 XAML 的样式中设置控件资源字典?
【发布时间】:2017-08-24 15:05:18
【问题描述】:

我在 Silverlight 中有一个带有一些边框的 UI,并且在该边框内有一个 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>     

【问题讨论】:

    标签: wpf xaml silverlight


    【解决方案1】:

    试试这个:

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

    这适用于 WPF。不过,在 Silverlight 中,恐怕您无法做到这一点。

    【讨论】:

    • 没有在silverlight中工作,正如你所说,我收到消息“成员“资源”无法识别或无法访问。”
    • 在 Silverlight 中,您的问题的答案是否定的,正如我在答案中所说的那样。不支持您尝试执行的操作。
    猜你喜欢
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多