WPF Relative Image Path Problem

While I was diving into developing my application, ThePen, I encountered a significant issue with loading images using relative paths in both XAML and code-behind. I suggest a solution for this issue. I cannot guarantee that it will work for you, but I hope it helps. The processes that I couldn't easily resolve, and that you might easily disregard, will be highlighted in red.


In case of XAML, if you want to show static images (not changed in runtime).

1. Place your image on your project directory. The image should truly exist, and also add your project. You can make folder and place them in there.

2. Normally add your image element like:

<Image Source="/Images/pen.png"/>


3. Double click the project name in Solution Explorer, you will see a xml document for project settiong . add following in the middle of the xml:

<ItemGroup>

<Resource Include="Images/pen.png" />

                   .... (add more images as you want)

</ItemGroup>

I should add all images like this and it worked fine.


In case of code behind, if you want to show dynamic images (changed in runtime).

1. Place your image next to ***.exe file. It may be placed in

SolutionDir/PorjectDir/bin/Debug/TargetFramework/***.exe


2. Your code should be like:

var bitmapImage = new BitmapImage();

bitmapImage.BeginInit();

bitmapImage.UriSource = new Uri("pen.png", UriKind.RelativeOrAbsolute);

bitmapImage.CacheOption = BitmapCacheOption.OnLoad;

bitmapImage.EndInit();

MyImage.Source = bitmapImage;



I spent hours to find these solution...... ah.

0 comments:

댓글 쓰기

Powered by Blogger.