[英]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
的見解,分析這兩種情況以及是否可行。
話雖如此,我認為不可能通過將樣式設置為資源來定義樣式的屬性。
您實際上正在尋找的是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.