wengseng
wengseng

Reputation: 1328

Image Source does not locate image file in working directory

I'm new to WPF, facing a problem in locating an image file on a button.

It's not working when I put a relative path, as shown(Window1.xaml):

<Button Height="23" HorizontalAlignment="Right" Margin="0,33,38,0" Name="button1" VerticalAlignment="Top" Width="24" Background="AliceBlue" OpacityMask="Cyan" Grid.Column="1" Click="button1_Click">
    <Image Source="Folder-icon.png"></Image>
</Button>

However, it's working when i put an absolute path:

<Button Height="23" HorizontalAlignment="Right" Margin="0,33,38,0" Name="button1" VerticalAlignment="Top" Width="24" Background="AliceBlue" OpacityMask="Cyan" Grid.Column="1" Click="button1_Click">
    <Image Source="D:\Folder-icon.png"></Image>
</Button>

I try to describe my folder structure in picture. Folder Structure

Hope someone can guide me to load the image to the button within the same workspace using relative path.

Upvotes: 2

Views: 5092

Answers (2)

CodeNaked
CodeNaked

Reputation: 41393

If you compare the Image.Source values for both cases, you will see in the cast that it does work the underlying Uri looks like:

file:///D:/Folder-icon.png

In the case where it does not work, the Image.Source value is null. The problem is that without the full path, WPF assumes it is a relative path to an embedded resource, not a file on disk.

This link provides a detailed description of URIs. But you'd need to use something like the following to use relative paths.

pack://siteoforigin:,,,/Folder-icon.png

One other note, the default path will be in the <Your Project Path\bin\Debug folder, not the <Your Property Path> folder.

Upvotes: 1

Afnan Bashir
Afnan Bashir

Reputation: 7419

if is because you are not giving it correct path .Here is sample

/EmailScrapperWpf;component/Images/SearchDog.gif

it is like /projectname;then path where your image is placed

i think in your case it should be

 <Image Source="/WPF1;Folder-icon.png"></Image>

when you Select image from the properties when you select the Image and press F4 there source navigate to the image then see what path is displayed after selecting the image and you have to place that path in Source=""

Upvotes: 1

Related Questions