iblog 5

苹果有iphone,我有iblog

导航

wpf使用资源字典组织资源

Posted on 2012-06-13 12:46  cbtech  阅读(248)  评论(0编辑  收藏  举报

如果希望在多个项目之间共享资源,可以创建一个资源字典。资源字典是一个存储希望使用的资源的XAML文档。下面是一个资源字典的示例,Dictionary1.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib"
                    >
    <sys:String x:Key="str3" >中国str3</sys:String>
</ResourceDictionary>

 

为了使用资源字典,需要将其合并到应用程序中某些位置的资源集合中。例如,可以放置到窗口的资源集合中,但是通常将其合并到应用程序的资源集合中,如下所示:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml"></ResourceDictionary> 
                <ResourceDictionary Source="其它资源词典文件"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
            <sys:String x:Key="str2">中国str2</sys:String>
        </ResourceDictionary>
    </Window.Resources>

    <Grid>
        <Button Content="确定" Height="23" HorizontalAlignment="Left" Margin="119,142,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="159,67,0,0" Name="textBox1" VerticalAlignment="Top" Width="120"  />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="280,142,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
    </Grid>
</Window>

上面的标记通过显式地创建一个ResourceDictionary对象进行工作。资源集合总是ResourceDictionary对象,但是这只是为了显式指定细节从而可以设置ResourceDictionary. MergedDictionaries属性的一种情况(该属性通常为空)。

MergedDictionaries集合是一个ResourceDictionary对象的集合,可以使用该集合提供自己想要的资源集合。如果希望添加自己的资源,并合并到资源字典中,只需要在MergedProperties部分之前或之后放置您的资源就可以了。

 

后台访问资源:

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            textBox2.Text = this.FindResource("str3").ToString();

        }

 

在前面介绍过,在不同但是相互重叠的资源集合中保存同名的资源是完全合理的。然而,合并使用相同资源名称的资源字典是不允许的。如果使用了相同的资源名称,当编译应用程序时就会收到一个XamlParseException异常。