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

    最近学习dotnet多语言资源的设置,很多地方没有搞清楚,于是参考msdn写了点代码验证下想法。

    测试程序是一个wpf默认程序,语言和资源均不做设置。

    字符串资源

    在默认资源文件中添加一条string1=teststring,编译之后用工具查看程序集可以发现字符串资源保存在名为"MySampleApp.Properties.Resources.resources"的资源中,其中MySampleApp为程序集的命名空间,"Properties.Resources"是默认资源文件的名称,".resources"是资源扩展名。

    读取此字符串资源代码如下:

    //直接调用资源编辑器生成的类方法
    Mywindow.Title =  MySampleApp.Properties.Resources.string1;

    //或者使用通用方法
    var rm = new ResourceManager("MySampleApp.Properties.Resources", Assembly.GetExecutingAssembly());
    Mywindow.Title 
    = rm.GetString("string1");


    读取字符串资源的xaml代码如下:

    <StackPanel Name="root"
               xmlns
    ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
               xmlns:x
    ="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:res
    ="clr-namespace:MySampleApp.Properties"
               x:Class
    ="MySampleApp.MyPage">
    <TextBlock Name="Text1" Text="{x:Static res:Resources.string1}"></TextBlock>
    </StackPanel>

     注意如果想让上面的xaml代码能正常读取系统默认字符串资源,需要设置资源访问属性为public,如图所示:

     

    图片资源

    在资源编辑器中添加一个png图片,名为img,资源中的图片格式为System.Drawing.Bitmap。

    读取img就是调用rm.GetObject("img"),返回对象是Bitmap类型,此对象无法直接用在WPF的Image控件上,必须做一些转换工作,转换Bitmap为BitmapImage.

    var rm = new ResourceManager("MySampleApp.Properties.Resources", Assembly.GetExecutingAssembly());          
    var bmp 
    = rm.GetObject("img"as Bitmap;
    var stream 
    = new MemoryStream();
    var bi 
    = new BitmapImage();
    bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
    bi.BeginInit();
    bi.StreamSource 
    = stream;
    bi.EndInit();
    image1.Source 
    = bi;

    第二种方法:转换Bitmap为BitmapSource.

    IntPtr bmpPt = bmp.GetHbitmap();
    System.Windows.Media.Imaging.BitmapSource bitmapSource 
    = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
        bmpPt, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    bitmapSource.Freeze();
    DeleteObject(bmpPt);
    image1.Source 
    = bitmapSource;

    [System.Runtime.InteropServices.DllImport(
    "gdi32.dll")]
    private static extern int DeleteObject(IntPtr o);

  • 相关阅读:
    爬虫相关
    进程、线程、协程
    经典排序算法详细介绍
    Pyhton学习-Python与中间件之Memcache(4)
    Python学习-Python操作数据库之MongoDB(2)
    Python学习-Python操作数据库之MySQL(1)
    人工智能安全(一)——初识人工智能
    Windows应急响应和系统加固(12)——SQL Server/MySQL/Oracle日志提取和安全分析
    Windows应急响应和系统加固(11)——Weblogic各类漏洞的日志分析和调查取证
    Windows应急响应和系统加固(10)——Nginx日志分析以及JBoss日志分析
  • 原文地址:https://www.cnblogs.com/xwing/p/1490240.html
Copyright © 2011-2022 走看看