'C# IOException Cannot locate resource

I have a C# project where I have some PNG files in a Images directory.

The structure of the project can be simplified to:

|
ViewModel.cs
View.xaml
|
[Images]
    \
    MapImageLayer16.png

In my view I bind to an object containing a string property ImagePath, pointing to ../Images/MapImageLayer16.png, and another string property Name:

<ListBox x:Name="DataLayerList" ItemsSource="{Binding LayersFiltered, Mode=OneWay}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Path=ImagePath}" Height="16"/>
                <TextBlock Text="{Binding Path=Name}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Now, the name comes trough fine. However, the image fails with the following description:

Failed to convert value '/Images/MapImageLayer16.png' (type 'String') to the target type using converter 'TargetDefaultValueConverter'. The fallback value will be used if it's available. IOException:'System.IO.IOException: Cannot locate resource 'images/mapimagelayer16.png'.

I tried all sorts of things by now:

  • changed the string value to ../Images/MapImageLayer16.png
  • changed the string value to pack://application:,,,/Images/MapImageLayer16.png
  • switched from string to Uri

Nothing works! How can I get the PNGs to show?



Solution 1:[1]

  1. This is a common error when we forget to set the properties of the image as a Resource (on VisualStudio, Rightclic on the image > Properties > Build Action : Resource & Copy to OutputDirectory : Do not copy)

  2. You also need to bind a BitmapImage, and not a string, to the Xaml Image control. In your CS code, the ImagePath must become :

    public BitmapImage Source => new BitmapImage(new Uri(ImagePath, UriKind.Relative));
    

with ImagePath = "/Images/MapImageLayer16.png"

Solution 2:[2]

This looks like a typical WPF resource error to me. Open the {projectname}.csproj file and add this (adjust if necessary if the structure is not correct)

  <ItemGroup>
    <Resource Include="Images\MapImageLayer16.png" />
  </ItemGroup>

Not in "PropertyGroup" but in "Project" as it can be seen here

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 xspirata
Solution 2 Schecher_1