Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change image.source with C# when creating a UWP app?

I'm developing my first Windows 10 UWP app. I have an image. This is its XAML code:

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

And im trying to change image.source with this code:

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

But when I compile the code I get this error pointing to the variable declaration:

UriFormatException was unhandled by user code

like image 735
Sam Williamson Avatar asked May 13 '16 17:05

Sam Williamson


1 Answers

Windows Runtime APIs do not support URIs of type UriKind.Relative, so you typically use the signature that infers the UriKind and make sure you've specified a valid absolute URI including the scheme and authority.

To access files stored inside the application package, but from code where there is no inferred root authority, specify the ms-appx: scheme like following:

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

For more info, please see How to load file resources (XAML) and URI schemes.

like image 73
ZORRO Avatar answered Oct 18 '22 15:10

ZORRO