如何在WP应用程序中全局定义颜色资源
本文关键字:全局 定义 颜色 资源 应用程序 WP | 更新日期: 2023-09-27 18:21:44
我想在WindowsPhone 8.1 Silverlight应用程序的单独文件中定义我的颜色和样式。我的文件:
Colors.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="AppColor1Brush">#1D8530</SolidColorBrush>
</ResourceDictionary>
Styles.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="Text1Style" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource AppColor1Brush}" />
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="FontSize" Value="{StaticResource PhoneFontSizeNormal}"/>
</Style>
</ResourceDictionary>
然后在我的App.xaml文件中,我尝试合并这些资源字典:
应用程序xaml
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyProject;component/Resources/Colors.xaml" />
<ResourceDictionary Source="/MyProject;component/Resources/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
但这行不通。我得到以下异常:
类型的第一次机会例外中发生"System.Windows.Markup.XamlParseException"System.Windows.ni.dll
附加信息:找不到具有名称/密钥的资源AppColor1Brush
当我将"颜色定义"从Colors.xaml移动到Styles.xaml时,一切都正常工作。所以我的问题是:这可能吗?我应该使用StaticResource
以外的东西吗?提前感谢
您必须在Styles.Xaml中引用Colors.Xaml,就像您在那里使用StaticResource引用一样。每个xaml资源字典都需要在MergedDictionaries中提供其所有引用(StaticResources)。
将Styles.Xaml修改为:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyProject;component/Resources/Colors.xaml" />
<!-- Also add the resource reference for your font style PhoneFontSizeNormal -->
</ResourceDictionary.MergedDictionaries>
<Style x:Key="Text1Style" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource AppColor1Brush}" />
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="FontSize" Value="{StaticResource PhoneFontSizeNormal}"/>
</Style>
</ResourceDictionary>