Wednesday, April 6, 2011

WPF, Image MouseDown Event

I have an control with a mouse down event where Id like to chnage the Image when the image is clicked. But I cant seem to alter ANY of the images properties in the event.

Event

    private void Image_MouseDown(object sender, MouseButtonEventArgs e)
    {
        BitmapImage bitImg = new BitmapImage();
        bitImg.BeginInit();
        bitImg.UriSource = new Uri("./Resource/Images/Bar1.png", UriKind.Relative);
        bitImg.EndInit();

        ((Image)sender).Source = null;
        ((Image)sender).Width = 100;
        ((Image)sender).Visibility = Visibility.Hidden;
    }

The event does fire, and even the .Visibility property does not alter the image and make it hidden.

What am I doing wrong?

From stackoverflow
  • Assuming the file is in your application, you need to use the Pack URI scheme:

            var img = sender as Image;
            BitmapImage bmp = new BitmapImage(new Uri("pack://application:,,,/Resources/Images/Bar1.png"));
            img.Source = bmp;
    

    In the above example, this would indicate a subfolder in your project of Resources/Images.

    PrimeTSS : hmmm Still doesnt change, I have the Bar1.png in a folder /Images/Bar1.pgn and have its property set as a Resource If I deliberatly miss spell the image to barx.png and exeption is thrown saying it cant locate it, so I know its finding it in the resources... Just does not actually update the image to the new one
    Joel Cochran : Looking again at your code, you are setting the source to null. I don't see where you are applying the BitmapImage to the Source?
    PrimeTSS : APPOLOGIES!!!!!!!! Ive found out why. I have a two templates on this control one is a "Selected" template, I didnt set the mouse down event on this template. Even though the event fired, I think the selected template over wrote the non-selected template that possibly chnaged the bit map but didnt live long enough to display and was over written by the selected template..... Thankyou!
    PrimeTSS : The null was just in debugging to see if it changed! Thnakyou for your help!! you have helped me find the issue, and wake up to the fact Ive over looked the problem was with code else where which i didnt post... Thankyou!
    PrimeTSS : I still dont get the different forms of uri("........ I wish there was a good white paper on it to understand it better
    Joel Cochran : The link in my post above is pretty decent, it outlines many different options.

0 comments:

Post a Comment