Oddities with paths in WPF
Published:
Remember relative/absolute paths? Image.Source
respects in a weird way the relative path a/b.png
vs the absolute (to the project’s root) path /a/b.png
and it’s useless.
The project directory structure:
- project root
- Images
- three-dots.png
- Dir
- WindowB.xaml
- WindowA.xaml
And the problematic paths:
See the difference?
WindowB doesn’t render the png because the window xaml file is located inside root/Dir
. WPF thinks you want three-dots.png
from root/Dir/Images/
when instead you want it from root/Images
.
My opinion is that it makes sense, but it’s useless. From my experience, everyone stores their assets in a single, common directory.
One path to rule them all
In case you want maximum, uncertainty-free paths, the syntax pack://application:,,,/<project namespace>;component/<path>
is valid.
In my case. pack://application:,,,/ScreenControlApp.Desktop;component/Images/three-dots.png
would also work (; my WPF app is named ScreenControlApp.Desktop
and the images are stored in root/Images/
).