如何在通用Windows平台应用程序中级联样式?

3

我又一次在处理UWP时遇到困难。看起来我无法在样式内部进行级联样式。这是UWP中不允许的吗?

这就是我的尝试...

        <Style x:Key="MainMenuRadioButtonStyle" TargetType="RadioButton">
            <Setter Property="Backgroud" Value="Grey"/>
            <Style.Resources TargetType="TextBlock">
                <Setter Property="Margin" Value="12,0,0,0"/>
            </Style.Resources>
        </Style>

然而,VS2015报错<Style.Resources>是无效的。我不想单独为RadioButton的内容中的TextBlock设置样式。
1个回答

2

在UWP(或XAML一般)中不支持级联样式。通常的做法是将可重用的样式/属性拆分并引用它们。

<Thickness x:Key="MyMargin">"12,0,0,0"</Thickness>

<Style x:Key="MainMenuRadioButtonStyle" TargetType="RadioButton">
    <Setter Property="Background" Value="Grey"/>
    <Setter Property="Margin" Value="{StaticResource MyMargin}" />
</Style>

您想要实现的是“修改”RadioButton的模板。您可以在此处找到完整的模板:https://msdn.microsoft.com/en-us/library/windows/apps/mt299147.aspx。如果您深入研究模板,您会看到这段代码:
<ContentPresenter x:Name="ContentPresenter"
        Content="{TemplateBinding Content}"
        ContentTransitions="{TemplateBinding ContentTransitions}"
        ContentTemplate="{TemplateBinding ContentTemplate}"
        Margin="{TemplateBinding Padding}"
        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
        Grid.Column="1"
        AutomationProperties.AccessibilityView="Raw"
        TextWrapping="Wrap" />

这是显示您的 RadioButton 实际内容的部分,正如您所看到的,它不是一个 TextBlock,而是一个 ContentPresenter(将文本显示为 TextBlock)。好消息是,此控件具有 Margin 属性,它取自模板的 Padding 属性值。因此,要达到您想要的效果,您可以简单地填写此属性:
<Style x:Key="MainMenuRadioButtonStyle" TargetType="RadioButton">
    <Setter Property="Background" Value="Grey"/>
    <Setter Property="Padding" Value="{StaticResource MyMargin}" />
</Style>

如果您想更改默认模板中不可用的属性,则必须创建自己的模板。


Bart,谢谢。你的开场白确认了我所预期的不可能,这真是太遗憾了。WPF中的XAML样式确实具有类似CSS的功能。我越是尝试在UWP中开发,就越感到沮丧。微软的标语“开发者最佳体验”简直是个笑话。没有Entity Framework支持,没有SQL Express,没有使用SQL Express的合并复制支持。工具箱中的控件也消失了,例如StatusBar、DataGrid和DockPanel。我的开发经验到目前为止非常缓慢和令人沮丧。无论如何,抱怨结束了,再次感谢。 - Ian GM
这仍然是一个沙盒环境(从头开始重写),所以你确实受到了限制。希望你能在某个时候学会适应它(我已经用了3年以上的时间来适应这个沙盒环境),并开始享受它 :) - Bart
尽管有些令人沮丧,但当我找到或开发出替代解决方案(例如编写自己的数据复制)时,这确实是令人满意的。干杯,Bart。 :) - Ian GM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接