Val M
Val M

Reputation: 929

How can I set the WPF BitmapImage UriSource property to a relative path?

I'm loading an image in WPF by using the BitmapImage class. My code works perfectly when I give an absolute path for the UriSource but not when I try and use a relative path.

My XAML is:

<Image Width="50" Name="MemberImage" HorizontalAlignment="Left">
    <Image.Source>
        <BitmapImage DecodePixelWidth="50" UriSource="questionmark.jpg" />
    </Image.Source>
</Image>

The questionmark.jpg is added to the project with a Build Action of Resource and Copy to Output Directory set to Copy always. The error I get is "The file [file name] is not part of the project or its 'Build Action' property is not set to 'Resource'". This works when I use an absolute path for the UriSource but that obviously won't do.

How should I be defining my UriSource in the XAML?

Upvotes: 7

Views: 22131

Answers (3)

Antonio N
Antonio N

Reputation: 46

Image files with the following options in properties
Build Action=Content
Copy to Output Directory=Copy if newer

<BitmapImage x:Key="QuestionMark" UriSource="pack://siteoforigin:,,,/questionmark.png"/>


Reference:
Xaml - Bitmap UriSource - absolute path works, relative path does not, why?

Upvotes: 3

Tae-Sung Shin
Tae-Sung Shin

Reputation: 20620

I don't think you need to copy the image to output directory once it's in resource.

Correct way to specify is

<BitmapImage 
    x:Key  = "Logo"
 UriSource = "pack://application:,,,/ApplicationNamespace;component/Images/App/image.png"  
/>

Just replace

ApplicationNamespace with your application namespace

and

Images/App/image.png with your image path in the project

Upvotes: 13

Dabblernl
Dabblernl

Reputation: 16141

I cannot reproduce the problem on my computer:

  • I add the jpg by choosing Add existing item in the Project menu
  • I then set its Build Actio to Resource and Copy to Output directory to always.
  • My XAML is the same.

Works perfectly here, even after moving the .exe and renaming the jpg. Something else must be biting you!

Upvotes: 0

Related Questions