WPF - Resources

When you create a WPF application, there is a time when you need to add resources to your application such as image, text file, xml file and etc. When you specify the source for this resources, you can either point it to the absolute path or relative path. Absolute path is the exact location while relative path is the location depending on your current working directory.

For example,

Current working directory - C:\Projects\MyApplication
Absolute path - C:\Projects\MyApplication\Resources
Relative path - .\Resources
Absolute path - C:\Projects\MyApplication2\Resources
Relative path - ..\MyApplication2\Resources

When your application is using a resource, you can either point it to the path or embed the resource inside your application. For example, you wan to show an image in your application with directly pointing to the sources

<image Source="C:\Projects\MyApplication\Resources\blank.jpeg">

or embedding the image inside your application

<image Source="/MyApplication;component/blank.jpeg">

Source format: "/project name;component/image-relative-path"

Note: To embed the image, in solution explorer, right click on the project node and click add existing item, browse to the image you want and add. Right click on this image file and select property, make sure the build action is set to resource.

The image can also be added to the properties.resources at the solution explorer, but you will need to convert it to BitmapImage as the image is saved as Bitmap. You can also add string as normal variable and others file type to properties.resources. To access it later in c# code-behind, you just call


string str = Properties.Resources.string-name-you-put;
Bitmap bmp = Properties.Resources.bitmap-name-you-put;

0 comments:

Post a Comment

top