How to Update/replace image in WFP by clicking button

Total Post:135

Points:947
WPF 
WPF
 1502  View(s)
Ratings:
Rate this:

So I have an image that when the user clicks on a button it will change it to a new item. However, whenever the user clicks on one of the button, the window will go blank. How can I get this to work? Thank you.

private void Next_Click(object sender, RoutedEventArgs e)
{
    if (imageNumber > 6)
    {
        imageNumber = 1;
    }
    imageNumber++;
    string sUri = string.Format("@/Resources/{0}", imageSource[imageNumber]);
    Uri src = new Uri(sUri, UriKind.Relative);
    var bmp = new BitmapImage(src);
    img.Source = bmp;           
}

Xaml Code:-

<Image x:Name="img">
    <Image.Source>
        <BitmapImage UriSource="Resources/BlackJackTut-1.jpg" />
    </Image.Source>
</Image>
  1. Post:378

    Points:2694
    Re: How to Update/replace image in WFP by clicking button

    Hi Chintoo,


    In WPF application you can do same also with "pack://application:,,,/resources/imagename.png".

    This way called Pack URI. This is static, but with these code you can do same an even use resource ;)

    Put image in Resources.

    private BitmapImage ConvertBitmapToBitmapImage(System.Drawing.Bitmap bitmap)
    {
        MemoryStream memoryStream = new MemoryStream();
        bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.StreamSource = new MemoryStream(memoryStream.ToArray());
        bitmapImage.EndInit();
        return bitmapImage;
    }

    and then use this:

    private void btn_Click(object sender, RoutedEventArgs e)
    {
        this.Img.Source = ConvertBitmapToBitmapImage(Properties.Resources.iamge1);
    }

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

Answer