ADDING IMAGE IN RUN TIME

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
WPF
 1100  View(s)
Ratings:
Rate this:

 I want to add an image from my Resources to an Image on the press of a Button.

Using Image1.Source = Properties.Resources.MyImage Does not work because the Image1 is of type ImageSource and the Left side is of type Drawing. How can I fix this code to display the image in my resource to the Image on button press?

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Adding Image in Run Time

    Hi ankit,

    This seems to work:

    In app.xaml:

    <Application.Resources>
        <Image x:Key="myImage" Source="C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"/>
    </Application.Resources>

    in MainWindow.xaml:

    <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Grid x:Name="myGrid" Margin="5" Width="500">
        <StackPanel>
            <Button Content="Load Picture" Click="Button_Click_1"/>
            <Image x:Name="ImageHolder"/>
        </StackPanel>
    </Grid>

    in button click event:

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Image img = Application.Current.Resources["myImage"] as Image;
            ImageHolder.Source = img.Source;
        }

    So in your code you need to do :

    Image myImage = Properties.Resources.MyImage as Image;

    Image1.Source = myImage.Source;

      Modified On Mar-31-2018 01:43:33 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!