Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# WPF URI syntax

Tags:

c#

wpf

I am just learning c# and have been struggling to work with URIs in WPF. I've googled around a fair bit but not having much luck.

Essentially I'm trying to have a BitmapImage object stored as a property in a Car object. I then want to display the BitmapImage in an Image control on a WPF form.

The app is a simple app (it's for a Uni assignment), so no database, etc.

I have two methods of doing this. The first is that I'm preloading Car data from a text file, including the filename of the JPG I want to load. I have included the JPG in a directory called Files which is off the main directory where my source code and class files are. I have set the JPG file to 'Content' and 'Always copy'. When I run a Debug, it copies the Files directory and the JPG to the debug\bin directory.

My code creates a BitmapImage by referring to the JPG using a URI as follows;

BitmapImage myImage = new BitmapImage (new Uri("Files/" + Car.Imagefilename, UriKind.Relative);
Car.Image = myImage;
ImageControl.Source = myImage;

If I step through this code in the debugger, it sometimes works and displays the image, but most of the time it doesn't.

My second method is when a user creates a new Car. This method always works. In this one, I use a file dialog box (dlg) to select the image and use an absolute path.

BitmapImage myImage = new BitmapImage (new Uri(dlg.Filename, UriKind.Absolute);
Car.Image = myImage;
ImageControl.Source = myImage;

So....I can't work out why the first method doesn't work. I think it's got something to do with the relative reference, but I can't work out how to syntax that properly to work. I've tried using "pack:,,,", I've tried adding "component", I've tried an '@' before the "pack". I can't seem to find something that explains this simply.

Apologies if this is straight forward but it's doing my head in! Appreciate any pointers.

like image 616
Nick S Avatar asked Oct 19 '25 11:10

Nick S


1 Answers

If the image files are located in a "Files" folder of your Visual Studio project, you should set their Build Action to Resource (and Copy to Output Directory to Do not copy), and load them by a Resource File Pack URI:

var image = new BitmapImage(new Uri("pack://application:,,,/Files/" + Car.Imagefilename));
Car.Image = image;
ImageControl.Source = image;

There is no need to copy the files anywhere. Images are loaded directly from the assembly.

like image 66
Clemens Avatar answered Oct 21 '25 01:10

Clemens