【问题标题】:Casting BitmapImage to Image.Source将 BitmapImage 转换为 Image.Source
【发布时间】:2017-12-03 16:02:21
【问题描述】:

我目前被困在 Visual Studio 2017 中的一个项目中。以下代码用于在 .xaml 页面上设置 Image 组件的来源。

private void setImage()
    {
        var image = new Image();
        var imageUrl = @"http://ddragon.leagueoflegends.com/cdn/5.2.1/img/" +
        currentChamp.Image.Group + "/" + currentChamp.Image.Full;
        Debug.Write(imageUrl);
        BitmapImage bmi = new BitmapImage();
        bmi.BeginInit();
        bmi.UriSource = new Uri(imageUrl, UriKind.Absolute);
        bmi.EndInit();

        image.Source = bmi;
    }

这是要引用的代码。 ^^^

在我发现的所有其他问题中,类似与我所问的问题一致,这一直是我正在尝试做的正确/回答/批准的方式。但是,我收到了一个没有人在任何问题中都没有收到的错误

无法将 system.windows.media.imaging.BitmapImage 隐式转换为 Windows.UI.XAML.media.ImageSource

我的导入、引用和类型都已经过检查并且是正确的。我错过了一个框架吗?是否有可能导致此功能不再起作用的更新?

我正在使用 VS2017 在 Microsoft.NETCore.UniversalWindowsPlatform 中工作

请注意,这不是 this 的重复项,因为我没有引用资源文件夹并且我的路径是绝对路径。

【问题讨论】:

    标签: c# image xaml url bitmapimage


    【解决方案1】:

    Windows.Media.Imaging.BitmapImage 是一个 WPF 类。 Windows.UI.XAML.media.ImageSource 是 UWP。您找到了 WPF 的解决方案,但您的 UWP Image 类需要一个 UWP 位图对象。你需要使用 Windows.UI.Xaml.Media.Imaging.BitmapImage 的东西。

    我目前无法测试 UWP,但通过阅读文档,我认为您想要这样的东西:

    image.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(imageUrl, UriKind.Absolute));
    

    您的 C# 文件中似乎有 using Windows.Media.Imaging;。将其替换为 using Windows.UI.Xaml.Media.Imaging;

    是明智的

    那么你可以使用这个:

    image.Source = new BitmapImage(new Uri(imageUrl, UriKind.Absolute));
    

    【讨论】:

    • 这和你的例子一样完美。非常感谢,我永远不会抓住它。我对 c# 比较陌生,调试是我最大的挑战。
    【解决方案2】:

    此处的错误消息会告诉您确切的问题所在。你在 UWP 项目中使用非 UWP BitmapImage。摆脱您对System.Windows.Media.Imaging 的使用,并将其更改为Windows.UI.Xaml.Media.Imaging。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-23
      • 2011-08-07
      • 2011-08-28
      • 2012-12-08
      • 1970-01-01
      • 2018-02-19
      相关资源
      最近更新 更多