以编程方式设置图像的来源(XAML)

我正在开发Windows 8应用程序。 我需要知道如何以编程方式设置图像的来源。 我认为Silverlight方法可行。 但事实并非如此。 有人知道怎么做这个吗? 以下内容不起作用:

string pictureUrl = GetImageUrl(); Image image = new Image(); image.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(pictureUrl, UriKind.Relative)); image.Stretch = Stretch.None; image.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left; image.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center; 

我得到一个exception,说:“给定的System.Uri无法转换为Windows.Foundation.Uri。”

但是,我似乎无法找到Windows.Foundation.Uri类型。

我刚试过

 Image.Source = new BitmapImage( new Uri("http://sofzh.miximages.com/c%23/image.jpg", UriKind.Absolute)); 

它没有问题……我在这里使用System.Uri 。 也许你有一个格式错误的URI或你必须使用绝对URI并使用UriKind.Absolute而不是?

这是我用的:

 string url = "ms-appx:///Assets/placeHolder.png"; image.Source = RandomAccessStreamReference.CreateFromUri(new Uri(url)); 

好吧, Windows.Foundation.Uri记录如下:

.NET:此类型显示为System.Uri。

所以棘手的一点就是不将它转换成Windows.Foundation.Uri自己 – 看起来WinRT会为你做这件事。 看起来问题在于您正在使用的URI。 在这种情况下它有什么关系? 我怀疑你真的只需要找到正确的URI格式。

检查你的pictureUrl,因为它是导致exception的原因。

但这也应该有效

 img.Source = new BitmapImage(new Uri(pictureUrl, UriKind.Absolute)); 

它应该与Windows.Foundation.Uri无关。 因为winrt会为你处理它。

此示例使用FileOpenPicker对象来获取存储文件。 您可以使用任何方法来访问文件作为StorageFile对象。

徽标是图像控件的名称。

参考以下代码:

  var fileOpenPicker = new FileOpenPicker(); fileOpenPicker.ViewMode = PickerViewMode.Thumbnail; fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; fileOpenPicker.FileTypeFilter.Add(".png"); fileOpenPicker.FileTypeFilter.Add(".jpg"); fileOpenPicker.FileTypeFilter.Add(".jpeg"); fileOpenPicker.FileTypeFilter.Add(".bmp"); var storageFile = await fileOpenPicker.PickSingleFileAsync(); if (storageFile != null) { // Ensure the stream is disposed once the image is loaded using (IRandomAccessStream fileStream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read)) { // Set the image source to the selected bitmap BitmapImage bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(fileStream); Logo.Source = bitmapImage; } } 

试试这种格式:

 ms-appx:/Images/800x600/BackgroundTile.bmp 

给定的System.Uri无法转换为Windows.Foundation.Uri

  var file = await KnownFolders.PicturesLibrary.GetFileAsync("2.jpg"); using(var fileStream = (await file.OpenAsync(Windows.Storage.FileAccessMode.Read))){ var bitImg= new BitmapImage(); bitImg.SetSource(fileStream); Img.Source = bitImg; }