Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

I’m working with C#/WPF, trying to insert an image onto a canvas. The image is located in the root directory. It is rendered on the canvas when I use the complete path but not when I use; Source= MyImage.png . Am I missing something?

HTML
<Canvas  Background="Wheat" UseLayoutRounding="False" AllowDrop="True" >
   <Image Canvas.Left="102" Canvas.Top="122" Width="400" OpacityMask="#FFC2E5DB"
          Source="C:/Users/Tip/C# Files/BookKeeper/MYImage.png"/>
</Canvas>

"MyImage" appears on the Canvas.

HTML
 <Canvas  Background="Wheat" UseLayoutRounding="False" AllowDrop="True" >
    <Image Canvas.Left="102" Canvas.Top="122" Width="400" OpacityMask="#FFC2E5DB"
           Source="MYImage.png"/>
 </Canvas>

The program runs normally but "MyImage" does not appear on the Canvas.

Any help would be greatly appreciated.
Posted
Updated 12-Nov-19 22:56pm

1 solution

Of course, using the full path is not a solution; the file won't be found on another system and the solution would not be portable even on yours.

First of all, you don't have to have the file in executable directory at all. If this is a permanent file, part of your product, you should better embed it in a resource and then reference in XAML using the URI scheme "pack://". See, for example:
http://www.wpfsharp.com/2012/01/23/using-relative-path-images-included-as-content-with-wpf[^].

Moreover, with WPF, I'm not sure you need to use pixel graphics at all (except the window and application menus). If the image is not extremely small, vector graphics is much easier and better, will be automatically zoomable, without the loss in quality, take up less memory, and so on. You can create vector image and save it to XAML (I highly recommend open-source InkScape, an application of amazing quality and performance) and embed it in your XAML, of window, resource dictionary, anything. You can find such example with the explanation, say, in my recent article: Practical Sound Recorder with Sound Activation[^].

If you still think you need to stay with pixel image, please see first line above, and also:
http://stackoverflow.com/questions/1444699/wpf-relative-image-source-path[^],
http://social.msdn.microsoft.com/Forums/vstudio/en-US/53cda8b8-08c1-4477-937a-e934157b0b1e/how-to-use-relative-path-for-image-in-wpf-when-image-is-not-in-project-directory?forum=wpf[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900