2016-05-13 40 views
5

我正在开发我的第一个Windows 10 UWP应用程序。我有一个形象。这是它的XAML代码:如何在创建UWP应用程序时使用C#更改image.source?

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

和IM试图改变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是由用户代码未处理

回答

0

您需要为每个URI对象指定附加的UriKind参数,以便将它们定义为Relative,例如

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

嗨,感谢您的帮助。但是这导致ArgumentsException被用户代码处理。有任何想法吗?谢谢 –

+1

看看这个类似的问题:[链接](http://stackoverflow.com/questions/32314799/uwp-image-uri-in-application-folder) – RobertoB

+0

嗨,是不是真的很多使用。不管怎么说,还是要谢谢你。 –

3

Windows运行时API不支持型UriKind.Relative的URI的,所以你通常使用推断UriKind签名,并确保您指定一个有效的绝对URI,包括方案和权威。

访问存储在应用程序包中的文件,但是从代码中没有推断的root权限,指定MS-APPX:方案类似以下内容:

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

欲了解更多信息,请参见How to load file resources (XAML)URI schemes

相关问题