Search code examples
c#xamlwindows-phone

Image source changing in C# for windows phone 8.1 RT


I want to change image source in runtime using C#. I tried this.

In the MainPage.xaml,

<Image x:Name="myImage" HorizontalAlignment="Left"
               Height="125"
               Margin="86,76,0,0"
               VerticalAlignment="Top"
               Width="220" />
        <Button Content="Button"
                HorizontalAlignment="Left"
                Margin="134,230,0,0"
                VerticalAlignment="Top"
                Click="Button_Click"/>

and in the MainPage.xaml.cs

private void Button_Click(object sender, RoutedEventArgs e)
        {
            myImage.Source = new BitmapImage(new Uri("/Assets/WorldCupFlags/Sri_Lanka.png", UriKind.Relative));
        }

It shows no compile time error but when I run this and click the Button it shows an exception. It says "An exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll but was not handled in user code."


Solution

  • The hint is in the exception:

    The given System.Uri cannot be converted into a Windows.Foundation.Uri

    You need to use an absolute URI for Universal XAML apps:

    myImage.Source = new BitmapImage(new Uri(
      "ms-appx:///Assets/WorldCupFlags/Sri_Lanka.png", UriKind.Absolute));