Loupins
Loupins

Reputation: 9

How to add an image?

I want to know how I add an image in a wpf application in the c# code ?

I want to add this image :

<Image Name="imgRubanbleu" Source="Objet/rubanbleu.png" Height="19"
Margin="34,252,354,231" RenderTransformOrigin="0.5,0.5" />

On this image :

<Image Source="Images/terrain.png" Grid.Row="4" Grid.RowSpan="4" Grid.Column="0" MouseUp="Image_MouseUp_1"/>

When I click on it...

I tried to do this :

private void Image_MouseUp_1(object sender, MouseButtonEventArgs e)
    {
        Image myImage = new Image();
        myImage.Width = 200;

        // Create source
        BitmapImage myBitmapImage = new BitmapImage();

        // BitmapImage.UriSource must be in a BeginInit/EndInit block
        myBitmapImage.BeginInit();
        myBitmapImage.UriSource = new Uri(@"Objet/rubanbleu.png");
        myBitmapImage.EndInit();
        //set image source
        myImage.Source = myBitmapImage;
    }

(http://msdn.microsoft.com/en-us/library/system.windows.controls.image.aspx)

But It still doesn't work...

(Sorry for my english level, I usually work in french)

Upvotes: 0

Views: 132

Answers (2)

Clemens
Clemens

Reputation: 128136

In code behind you need to write a full Resource File Pack URI:

var uri = new Uri("pack://application:,,,/Objet/rubanbleu.png");

myImage.Source = new BitmapImage(uri); // BeginInit/EndInit not required!

This only works if the image files are part of your Visual Studio project (in a subfolder named Objet) and their Build Action is set to Resource.


That said, your new Image control myImage has to be added to your UI somewhere. You seem to want to put it on top of an existing Image, so you should add it to the same container, e.g. like this:

<Grid x:Name="imageGrid">
    <Image ... MouseUp="Image_MouseUp_1"/>
</Grid>

Code:

private void Image_MouseUp_1(object sender, MouseButtonEventArgs e)
{
    var myImage = new Image();
    ...
    imageGrid.Children.Add(myImage);
}

Upvotes: 1

Sheridan
Sheridan

Reputation: 69987

In WPF, we tend to use XAML rather than procedural code. Here is an example of an Image that has it's Source value changed as the user moves their mouse over it:

<Image Width="16" Height="16" Margin="3,0">
    <Image.Style>
        <Style TargetType="{x:Type Image}">
            <Setter Property="Source" Value="Images\DefaultImage.png"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="true">
                    <Setter Property="Source" Value="Images\MouseOverImage.png"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>

Now I'm aware that you wanted a change after a click, but this was just an example for you to get you started. You can find out more from the Trigger Class page on MSDN. You might also like to view the EventTrigger Class page on MSDN too... these enable us to handle events (such as your chosen MouseUp event) in Triggers.

Upvotes: 0

Related Questions