【WP8】ResourceDictionary

WP8中引用资源字典

  当我们定义的样式太多的时候,我们可以把样式分别定义在不同的文件中,然后通过 MergedDictionaries 应用到其他资源字典中,看下面Demo

 

  我们可以把样式定义在多个文件中,然后再App.xaml中引用

我们先定义三个文件

  1、蓝色按钮资源文件,定义按钮的Foreground为Blue

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Style TargetType="Button">
        <Setter Property="Foreground" Value="Blue"></Setter>
    </Style>
    
</ResourceDictionary>
BlueButtonResource.xaml

  2、红色按钮资源文件,定义按钮的Foreground为Red

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Style TargetType="Button">
        <Setter Property="Foreground" Value="Red"></Setter>
    </Style>
    
</ResourceDictionary>
RedButtonResource.xaml

  3、全局资源文件(在App.xaml引用),这里只定义TextBlock为Teal

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Style TargetType="TextBlock">
        <Setter Property="Foreground" Value="Teal"></Setter>
    </Style>

</ResourceDictionary>
GlobalResourceDictionary.xaml

 

然后再App.xaml全局引用全局资源文件

    <!--应用程序资源-->
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <!--这里引用其他文件,当然,也可以设置多个ResourceDictionary-->
                <ResourceDictionary Source="GlobalResourceDictionary.xaml"/>
            </ResourceDictionary.MergedDictionaries>
            
            <!--这里定义其他样式-->
            <Style TargetType="TextBlock">
                <Setter Property="Foreground" Value="Teal"></Setter>
            </Style>
            
            <Style TargetType="Rectangle">
                <Setter Property="Fill" Value="{StaticResource PhoneAccentBrush}"></Setter>
            </Style>
        </ResourceDictionary>
    </Application.Resources>

 

 前面蓝色和红色按钮的两个资源文件,可以用来当成不同的主题,我们可以在代码中动态加载

            ResourceDictionary resourceDictionary = new ResourceDictionary();
            //这里的Uri格式:/解决方案;component/资源文件路径
            Application.LoadComponent(resourceDictionary, new Uri("/LoadResourceDictionary;component/BlueButtonResource.xaml", UriKind.Relative));
            Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);

 

 

 

 

 

posted @ 2014-03-23 00:02  bomo  阅读(980)  评论(0编辑  收藏  举报