繁体   English   中英

在Uwp VisualState.Setters中使用StaticResource

[英]Use a StaticResource in Uwp VisualState.Setters

这是我的代码

<VisualState x:Name="Focused">
  <VisualState.Setters>
    <Setter Property="Background" Value="{StaticResource LightButtonBackground}"/>
    <Setter Property="Foreground" Value="White" />
  </VisualState.Setters>
</VisualState>

编译器说XamlCompiler error WMC0615: Type 'StaticResource' used after '{' must be a Markup Extension. Error code 0x09ff. XamlCompiler error WMC0615: Type 'StaticResource' used after '{' must be a Markup Extension. Error code 0x09ff. 我在网络上找不到任何有用的信息。 怎么了?

您在这里混合了Setter的两种用法。

只有在定义Style才能使用Property属性:

    <Style TargetType="TextBlock" x:Key="TextBlockStyle">
        <Setter Property="Foreground" Value="Navy"/>
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="VerticalAlignment" Value="Bottom"/>
    </Style>

在样式定义中,目标控件类型是已知的(由Style.TargetType提供)。

VisualState.Setters列表中,您没有定义Style 您正在更改某些现有子控件上的某些属性。 在这种情况下,您需要使用Target属性使XAML运行时知道您要定位的元素和属性。

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup>
            <VisualState x:Name="NarrowState">
                <VisualState.Setters>
                    <Setter Target="myPanel.Orientation" Value="Vertical"/>
                    <Setter Target="myPanel.Width" Value="380"/>
                    <Setter Target="myTextBlock.MaxLines" Value="3"/>
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>

    <StackPanel x:Name="myPanel" Orientation="Horizontal">
        <TextBlock x:Name="myTextBlock" MaxLines="5" Style="{ThemeResource BodyTextBlockStyle}"/>
    </StackPanel>
</Grid>

正如@Vincent答案所指出的那样,在视觉状态下定义设置器时,您没有正确使用它,而是在定义样式资源时像在使用那样。 不过,我的答案是关于如何在样式上使用定义的StaticResource的见解,分析这两种情况以及是否可行。


话虽如此,我认为不可能通过将样式设置为资源来定义样式的属性。

  • 如果您在资源上定义多个属性,将会发生什么? 然后,您如何才能为拥有多个样式属性的资源设置属性样式?
  • 如果您为背景定义了一个持有Color的资源,但是随后又使用该资源将其设置为依赖对象控件的前景,将会发生什么? 由于您要针对接受相同类型的属性,是否应该存在这种灵活性?

您实际上正在寻找的是BasedOn属性,该属性允许继承样式。 唯一的缺点是, Styles ,从其他样式继承必须针对同一类型的控制或者要么是从由基本样式有针对性的类型派生的控制。

在这里查看文档: https : //docs.microsoft.com/zh-cn/windows/uwp/design/controls-and-patterns/xaml-styles#use-based-on-styles

编辑:

不幸的是,我认为不可能使用BasedOn定义从资源继承的VisualState样式,因为我们被迫在其定义上指定每个设置器。 我们可能会遇到XY问题吗? 在资源定义上,如果要从样式继承,那将是一种方法,但实际上将其应用于视觉状态似乎又是另一回事了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM