Search code examples
c#wpfmenumenuitemimageicon

images cannot be displayed in the bare menu but not in the rest of the grid


I have the following wpf grid block. I have an image named truc.PNG, a small file image measuring 16x16 pixels. I can see it in the image block, but not as an icon in one of the menu bar items.I've tried various solutions found here (and not only) but the image never appears, even though the space seems to be ocupied. I've tried with a stackpannel, which had been validated in an old stackoverflow post, I've tried with the viewblock, I've also tried using the class properties in c# but each time the same result, the space seems to be taken but the icon is invisible.

<Menu Grid.Row="0">
    <MenuItem Header="Icon">
        <MenuItem Header="Sous icone">
            <MenuItem.Icon>
                <Image Source="LesImages/truc.PNG"/>
            </MenuItem.Icon>
        </MenuItem>
    </MenuItem>
    <MenuItem Header="Export" />
    <MenuItem Header="New record" />
</Menu>

<Image x:Name="ImBox" Source="LesImages/truc.png" HorizontalAlignment="Left" Height="63" Margin="82,39,0,0" VerticalAlignment="Top" Width="119" Grid.RowSpan="2"/>

Tried Stackpanel solution :

<MenuItem>
    <MenuItem.Header>
    <StackPanel>
            <Image Width="20" Height="20" Source="LesImages/truc.PNG" />
        <ContentPresenter Content="Reports" />
    </StackPanel>
</MenuItem.Header>
</MenuItem>

EDIT : I added the image as a project resource in the .csproj without changing the code and it solved the problem.

  <ItemGroup>
    <Resource Include="LesImages\truc.PNG" />
  </ItemGroup>

Solution

  • From your XAML code, it looks like the image should appear correctly.

    Here are things to check when everything looks right, but the image still isn't loading:

    1. Make sure that the path is correct in the Source property. In your case it probably is, since it shows in the image block but not the menu. You can ensure that the path is correct and that the image is properly associated with the project.

    See here: stackoverflow.com/q/25714085/1136211 – Clemens Dec 6 at 8:47

    1. If the image is intended to be embedded into the dll, is it properly added to the project? This can be check via the image properties in the solution explorer or by checking your .csproj file for something like:
      <ItemGroup>
        <Resource Include="LesImages\truc.PNG" />
      </ItemGroup>
    

    enter image description here

    1. Lastly, you can make sure that the scaling is set appropriately. This is probably not an issue in your case in the code as shown, since the default Stretch property value is Uniform. However if it was set to None, the image will render in the original size, and if the corner that fills the icon space is transparent or the same color as the background, it will appear to be invisible.
    <Image Source="LesImages/truc.PNG.png"
           Stretch="Uniform" />