Uri Formatting on Image Source

2019-07-07 05:15发布

问题:

What is wrong with the following uri?

bmi.UriSource = (new Uri(@"/Assets/Image.png", UriKind.Relative));

Where bmi is a BitmapImage.
I have the build action for the image set to Embedded Resource.

回答1:

Found it;

bmi.UriSource = (new Uri("ms-appx:/Assets/Logo.png"));

And build action set to Content. There's no Relative URI in RT.



回答2:

WPF needs to use the Resource build action (or Content build action) to use Uris. For binary data (like an image), use Binary.

If you're using a single project for your code (a single dll), you cvan skip the '/MYAPPLICATIONNAME;component/' and just use "Assets/Image.png" as a relative Uri.



回答3:

Each control or page has a BaseUri property which you can use to build the proper uri for assets.

Here is an example:

imageIcon.Source = new BitmapImage(new Uri(this.BaseUri, "Assets/file.gif"));

// Or use the base uri from the imageIcon, same thing
imageIcon.Source = new BitmapImage(new Uri(imageIcon.BaseUri, "Assets/file.gif"));