当创建一个UWP应用时,我该如何使用C#更改图像源(image.source)?

8

我是第一次开发Windows 10 UWP应用程序。我有一张图片,这是它的XAML代码:

<Image x:Name="image" 
               HorizontalAlignment="Left"
               Height="50" 
               Margin="280,0,0,25" 
               VerticalAlignment="Bottom" 
               Width="50" 
               Source="Assets/Five.png"/>

我尝试使用以下代码更改图像源:

image.source =

        private void slider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
    {
        BitmapImage One = new BitmapImage(new Uri(@"Assets/One.png"));
        BitmapImage Two = new BitmapImage(new Uri(@"Assets/Two.png"));
        BitmapImage Three = new BitmapImage(new Uri(@"Assets/Three.png"));
        BitmapImage Four = new BitmapImage(new Uri(@"Assets/Four.png"));
        BitmapImage Five = new BitmapImage(new Uri(@"Assets/Five.png"));

        if (slider.Value == 1)
        {
            image.Source = One;
        }
        else if (slider.Value == 2)
        {
            image.Source = Two;
        }
        else if (slider.Value == 3)
        {
            image.Source = Three;
        }
        else if (slider.Value == 4)
        {
            image.Source = Four;
        }
        else if (slider.Value == 5)
        {
            image.Source = Five;
        }
    }

但是当我编译代码时,会出现指向变量声明的错误:

用户代码未处理UriFormatException异常

2个回答

11

Windows Runtime API不支持类型为UriKind.Relative的URI,因此通常使用推断UriKind的签名,并确保指定了有效的绝对URI,包括方案和授权。

要访问存储在应用程序包内部的文件,但是从没有推断根授权的代码中,请指定ms-appx:方案,如下所示:

BitmapImage One = new BitmapImage(new Uri("ms-appx:///Assets/One.png"));

了解更多信息,请查看如何加载文件资源(XAML)URI 方案


0

您需要为每个URI对象指定附加的UriKind参数,以便它们被定义为相对路径,例如:

new Uri("Assets/One.png", UriKind.Relative)

1
嗨,感谢您的帮助。然而,这导致了“ArgumentsException was unhandled by user code”的错误。有什么想法吗?谢谢。 - Sam Williamson
1
请查看这个类似的问题:链接 - RobertoB
嗨,这并没有什么用处。不管怎样还是谢谢。 - Sam Williamson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接