我有许多用于字体大小,画笔等的全局常量。例如:
<x:Double x:Key="SmallWindowWidth">0</x:Double>
<x:Double x:Key="CompactWindowWidth">600</x:Double>
<x:Double x:Key="MediumWindowWidth">720</x:Double>
<x:Double x:Key="WideWindowWidth">1024</x:Double>
<x:Double x:Key="SmallTitleFontSize">22</x:Double>
<x:Double x:Key="NormalFontSize">16</x:Double>
当窗口宽度变小时,我想减少某些文本的FontSize。当然我可以单独定位它们中的每一个,但我宁愿做的是全局更改{StaticResource NormalFontSize},如下所示:
<VisualState x:Name="Small">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="{StaticResource SmallWindowWidth}" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="{StaticResource NormalFontSize}" Value="12"/>
</VisualState.Setters>
</VisualState>
......这似乎不起作用,因为它不属于财产。那么,有没有办法在XAML中改变静态资源(!)?
答案 0 :(得分:1)
嗯,你可以通过一些调整来做到这一点。 注意,我已经在UWP中进行了本地测试以回答您的问题,但我还没有在我发布的任何项目中使用它。
第一步,
如果您需要更改不具有依赖属性的资源,例如双值 [Wrapper Needed]
public class DoubleWrapper : DependencyObject
{
public double Value
{
get { return (double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
// Using a DependencyProperty as the backing store for Value. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(double), typeof(DoubleWrapper), new PropertyMetadata(0.0));
}
第二步, 除了强制x:Key之外,您还需要定义x:Name。能够在可视状态设置器中定位静态资源。 (如果需要,可以为x:Name使用不同的名称)
<Page.Resources>
<local:DoubleWrapper x:Name="FontSizeWrapper" x:Key="FontSizeWrapper" Value="12"/>
<SolidColorBrush x:Name="MainBrush" x:Key="MainBrush" Color="Red"/>
</Page.Resources>
最后,当您在Visual状态setter中更改FontSizeWrapper或MainBrush的Value属性时,它将更新所有绑定。
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="LayoutStates">
<VisualState x:Name="NarrowState">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="0"/>
</VisualState.StateTriggers>
<VisualState.Setters>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="WideState">
<VisualState.Setters>
<Setter Target="FontSizeWrapper.(DoubleWrapper.Value)" >
<Setter.Value>
<x:Double>25</x:Double>
</Setter.Value>
</Setter>
<Setter Target="MainBrush.(SolidColorBrush.Color)" Value="Aqua" />
</VisualState.Setters>
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="800"/>
</VisualState.StateTriggers>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<TextBlock Text="This is test" Foreground="{StaticResource MainBrush}"
VerticalAlignment="Center"
FontSize="{Binding Value, Source={StaticResource FontSizeWrapper}}"/>
</Grid>