开发者

How to Update/replace image in WPF by clicking button

So I have an image that whe开发者_开发知识库n 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

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


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);
}


Just make an Image outside the mainWindow.

Then:

myImageOnScreen.Source = myImageOffScreen.Source;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜