您的位置:首页 > 其它

WPF应用程序使用资源及多语言设置学习-1

2009-05-26 17:08 381 查看
最近学习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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: