编程方式设置的图像的源(XAML)(Programmatically set the Source

2019-06-25 21:36发布

我的工作在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;

我得到的是说,一个例外:“给定的System.Uri不能转换成Windows.Foundation.Uri。”

不过,我似乎无法找到Windows.Foundation.Uri类型。

Answer 1:

我只是想

Image.Source = new BitmapImage(
    new Uri("http://yourdomain.com/image.jpg", UriKind.Absolute));

和它的作品没有问题...我使用System.Uri这里。 也许你有一个畸形URI或你必须使用一个绝对URI,并使用UriKind.Absolute呢?



Answer 2:

这是我使用:

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


Answer 3:

那么, Windows.Foundation.Uri被证明是这样的:

.NET:这种类型的显示为的System.Uri。

所以有点棘手不是将其转换成Windows.Foundation.Uri自己-它看起来像的WinRT会替你。 它看起来像这个问题是您正在使用的URI。 这是什么相对于在这种情况下? 我怀疑你真的只需要找到一个URI正确的格式。



Answer 4:

本示例使用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;
        }
    }


Answer 5:

检查你的pictureUrl因为它是什么导致异常。

但这应该工作以及

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

它应该有无关Windows.Foundation.Uri。 因为WinRT中会为您处理。



Answer 6:

试试这个格式:

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

给定的System.Uri不能被转换成Windows.Foundation.Uri



Answer 7:

<Image Name="Img" Stretch="UniformToFill" />

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;
}


文章来源: Programmatically set the Source of an Image (XAML)