WPF(四)Application4:程序集资源

  WPF应用程序中的程序集资源和其他.net应用程序中的程序集资源在本质上是相同的。WPF程序集资源和其他应用程序中的程序集资源之间的重要区别是引用资源的寻址系统不同。

    1.添加资源

  可以通过向项目添加文件,并将其Build Action属性设置为Resource。

      

2.检索资源

  添加资源很简单,检索资源有多种方法:

    

            #region 检索资源

            //方法一:StreamResourceInfo对象
            StreamResourceInfo sri = Application.GetResourceStream(
                new Uri("images/Koala.jpg",UriKind.Relative)
                );
            //方法二:GetResourceStream方法
            Assembly assembly = Assembly.GetAssembly(this.GetType());
            string resourceName = assembly.GetName().Name + ".g";
            ResourceManager rm = new ResourceManager(resourceName,assembly);

            using(ResourceSet set=rm.GetResourceSet(CultureInfo.CurrentCulture,true,true)
            {
                UnmanagedMemoryStream s;
                
                s=(UnmanagedMemoryStream)set.GetObject("images/winter.jpg",true);
            }
            //通过ResourceManager类和ResourceSet类还可以完成其他一些Application类所不能完成的 
            //工作
            using(ResourceSet set=rm.GetResourceSet(CultureInfo.CurrentCulture,true,true))
            {
                foreach(DictionaryEntry res in set)
                {
                    MessageBox.Show(res.Key.ToString());
                }
            }

            //第三种简单的方法
            BitmapImage image=new BitmapImage(new Uri(@"d:\Image\image.jpg"));
            #endregion

          

   pack URI

  WPF使用pack uri语法寻址编译过的资源例如:

   images/winter.jpg  相对URI

   等同于:pack://application:,,,/images/winter.jpg

   1.访问其他程序集中的资源语法

    pack://application:,,,/AssemblyName:component/ResouceName

    例如:

   image.Source=new BitmapImage(new Uri("pack://application:,,,/ImageLibrary;component/Images/winter.jpg"));

   或者:

  image.Source=new BitmapImage(new Uri("ImageLibrary;component/images/winter.jpg",UriKind.Relative));

   如果使用强命名的程序集

  image.Source=new BitmapImage(new Uri("ImageLibrary;v1.24;component/iamges/winter.jpg"),UriKind.Relative));

  下面的示例使用了版本号和公钥标记

 iamge.Source=new BitmapImage(new Uri("ImageLibrary;v1.23;dc64a7fbd64912;component/images/winter.jpg",UriKind.Relative));

posted @ 2012-04-26 22:09  William Jiang  阅读(1369)  评论(0编辑  收藏  举报