Set an image

Asked

Viewed 167 times

3

I’m trying to set an image, but I’m not getting it. WPF can’t seem to find the image path. Why this happens?

<Image  Width="60"
        Height="60"
        Stretch="Fill"
        Source="\Images\Tiles\clientes.png" />
  • You can show me a screenshot of your Solution explorer pointing to the image?

2 answers

1

I had problems with a project of mine and really took a long time to find the solution, but what solved for me was to put the Source of the image this way:

<Image  Width="60"
        Height="60"
        Stretch="Fill"
        Source="/Nome.Do.Projeto;component/Images/Tiles/clientes.png"/>

Where Name.do.Project is the namespace of the project where the image is.

I hope I’ve helped.

0


Defining image by XAML

You are using the bars backwards. The correct one would be:

<Image  
    Width="60"
    Height="60"
    Stretch="Fill"
    Source="/Images/Tiles/clientes.png" />

It is also possible to create a Resource for the images and then use them as a StaticResource.

Inside the tag ResourceDictionary of the archive App.xaml add:

<BitmapImage x:Key="ImagemCliente" UriSource="/Images/Tiles/clientes.png" />

And in your image use that way:

<Image  
    Width="60"
    Height="60"
    Stretch="Fill"
    Source="{StaticResource ImagemCliente}" />

That way the code of your layout is cleaner and if you use the image in more than one place for example, when you want to modify it, you will have to change in only one location.

Defining Image through Binding

Create a property of type ImageSource in its class, which will be used to store the desired image. Assuming the property used is Caminho, then the image definition in the property would be as follows:

seuObjeto.Caminho = new BitmapImage(new Uri("pack://application:,,,/Images/Tiles/clientes.png"))

And the binding for XAML:

<Image  
    Width="60"
    Height="60"
    Stretch="Fill"
    Source="{Binding Caminho}" />

I don’t know how you defined the structure of binding in your project, then just put the property that should be made Binding. Depending on your architecture, the binding may be different, but the idea is the same.

.NET 4.5

If you are using . NET 4.5 and the previously reported paths do not work, you will need to use the full image path. This is due to the fact that Microsoft made significant modifications to this version of . NET and "spoiled" some things.

<Image Source="pack://application:,,,/AssemblyName;component/Images/Tiles/clientes.png">
  • But what about passing the paths through a property (String Path) and making a Binding, as I would?

  • I edited the answer and added what you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.