zoukankan      html  css  js  c++  java
  • WPF应用程序使用资源及多语言设置学习2

    WPF资源

    WPF资源使用其实的也是resources格式嵌入资源,默认的资源名称为"应用程序名.g.resources",不过WPF资源使用的pack URI来访问资源。

    添加图像资源

    在解决方案资源管理器中包含一个图像资源(如data\img.png)的时候,默认是输出为资源文件的(生成操作=Resource),编译的时候作为资源编译到程序集中;

    当在img.png的属性页中把"生成操作"属性设置为"内容",同时设置"复制到输出目录"属性为"如果较新则复制",则输出为内容文件,data\img.png会复制一份到程序集输出目录,这样无需编译就可以修改资源文件了。

    此图片资源的uri链接为"/data/img.png",如<Image Name="image3" Source="/data/img.png" />

    在资源字典中使用字符串

    ResouceDictionary中可以添加各种类型资源,使用如下方法来保存字符串到资源字典中。资源字典默认情况下会被编译成baml保存到"应用程序名.g.resources"资源中,也可以修改输出为内容文件方法同上。

    资源字典的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="rdstring1">resource dictionary string.</sys:String>
    </ResourceDictionary>


    别忘了在app.xaml中添加这个资源字典的引用:

    MergedDictionaries

    xaml代码中使用此字符串:

    <Label Content="{StaticResource rdstring1}" Name="label8" />


    代码中使用此字符串:

    string msg= (string)Application.Current.FindResource("rdstring1");
    MessageBox.Show(msg);

    加载程序集中的WPF资源

    先准备一个WPF资源类库:新建一个程序集,默认创建的东西都删掉,添加上面的资源字典dictionary1.xaml到类库中,编译为ClassLibrary1.dll,使用Reflector工具检查发现这个类库中资源名为:ClassLibrary1.g.resources,内容为dictionary1.baml,ok准备完毕。

    主程序集中无需引用这个资源库,只需要放在同一个输出目录下即可,在代码中加载此资源并合并到Application中。

    加载代码(相对URI):

    var uri = new Uri("/ClassLibrary1;component/Dictionary1.xaml", UriKind.Relative);
    var res 
    = (ResourceDictionary)Application.LoadComponent(uri);
    Application.Current.Resources.MergedDictionaries.Add(res);

    加载代码(绝对URI):

    var uri = new Uri("pack://application:,,,/ClassLibrary1;component/Dictionary1.xaml");
    ResourceDictionary res 
    = new ResourceDictionary {Source = uri};
    Application.Current.Resources.MergedDictionaries.Add(res);


    在XAML中直接加载:

    <Application 
        
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x
    ="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class
    ="MySampleApp.app">
        
    <Application.Resources>
            
    <ResourceDictionary>
                
    <ResourceDictionary.MergedDictionaries>
                    
    <ResourceDictionary Source="pack://application:,,,/ClassLibrary1;component/Dictionary1.xaml" />
                
    </ResourceDictionary.MergedDictionaries>
            
    </ResourceDictionary>
        
    </Application.Resources>
    </Application>


    使用资源方法同上,注意,后加载的资源会替换掉已有资源中相同名字的资源。

  • 相关阅读:
    Asp.net实现URL重写
    IHttpModule不起作用的两个原因
    从客户端中检测到有潜在危险的 request.form值[解决方法]
    PHP $_SERVER详解
    string.Format 格式化日期格式
    图解正向代理、反向代理、透明代理
    Javacard 解释器怎样在API类库中找到源文件调用的类、方法或者静态域?
    API
    指令集
    机器码与字节码
  • 原文地址:https://www.cnblogs.com/xwing/p/1493256.html
Copyright © 2011-2022 走看看