使用程序代码加载图片
读取资源的方法:Application.GetResourceStream(Uri uri): StreamResourceInfo
Page.xaml文件
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SilverlightApplication7.Page"
Width="640" Height="480">
<Grid x:Name="LayoutRoot" Background="White">
</Grid>
</UserControl>
Page.xaml.cs文件
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Resources;
using System.Windows.Media.Imaging;
namespace SilverlightApplication7
{
public partial class Page : UserControl
{
public Page()
{
// 需要初始化变量
InitializeComponent();
this.MouseLeftButtonDown += new MouseButtonEventHandler(Page_MouseLeftButtonDown);
}
void Page_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Image img = LoadImage("/SilverlightApplication7;component/1150810574.jpg");
LayoutRoot.Children.Add(img);
}
Image LoadImage(string relativeUrlString)
{
Uri uri = new Uri(relativeUrlString, UriKind.Relative);
StreamResourceInfo sri = Application.GetResourceStream(uri);
BitmapImage bimg = new BitmapImage();
bimg.SetSource(sri.Stream);
Image img = new Image();
img.Source = bimg;
return img;
}
}
}
使用代码加载文本
Uri uri = new Uri("/SilverlightApplication7;component/remark.txt", UriKind.Relative);
StreamResourceInfo sri = Application.GetResourceStream(uri);
System.IO.StreamReader reader = new System.IO.StreamReader(sri.Stream);
MessageBox.Show(reader.ReadToEnd());