Silverlight Tips of the Day 系列翻译与领悟#10
Silverlight Tip of the Day #10 – How to Dynamically Load and Display Images
在Silverlight中加载图片是非常方便的。第一步是创建Uniform Resource Identifier (URI)。URI本质上是指向资源的一个字符串。资源可以直接放在项目中,也可以放在Internet上。本地读取的图片需要直接加在工程中。
Image image = new Image();
Uri uri = new Uri("images/myImage.png", UriKind.Relative);
ImageSource img = new System.Windows.Media.Imaging.BitmapImage(uri);
image.SetValue(Image.SourceProperty, img)
为了显示图片,你需要将它添加到XAML中定义的元素的 Children 中。例如,如果你在Page.xaml中的Grid对象下创建了一个 Canvas 对象。把 x:Name 标签命名为 “Map”:
<Grid x:Name="MainGrid">
<Canvas x:Name="Map">
</Canvas>
</Grid>
现在回到Page.xaml.cs文件,你可以如下动态添加图片到你刚刚创建的canvas对象中:
Map.Children.Add(image);
另外,直接在XAML中定义image是一样的。例如:
<Image Source="images/MyImage.png"></Image>