Sergio Tapia Sergio Tapia - 7 days ago 5
C# Question

"Cannot convert string to ImageSource." How can I do this?

private void HeroMouseEnter(object sender, MouseEventArgs e)
{
((Image)sender).Source = GetGlowingImage(((Image)sender).Name);
}

public ImageSource GetGlowingImage(string name)
{
switch (name)
{
case "Andromeda":
return "HeroGlowIcons/64px-Andromeda.gif";
default:
return null;
}
}


I'm just trying to make an event to change the image according to where the mouse entered. But I cannot make this work.

Edit: I did this in Windows Forms and it work 100% like I want it to. How could I translate something like this in WPF?

void HeroMouseEnter(object sender, EventArgs e)
{
((PictureBox)sender).Image = GetGlowingImage(((PictureBox)sender).Name);
}


public Image GetGlowingImage(string name)
{
switch (name)
{
case "Andromeda":
return Properties.Resources._64px_Andromedahero___copia;
case "Engineer":
return Properties.Resources._64px_Engineerhero___copia;
default:
return null;
}
}

Answer

In your GetGlowingImage() method you need to generate a new ImageSource

This link might help: Setting WPF image source in code

Edit:

See the difference here is that in the WindowsForms code you have the Properties.Resources._64px_Andromedahero___copia is the name of an Image variable that contains the image data. In your WPF code the string "filename...." is not an image or image source it's just a string that represents the path to the file. You need to load the image file using that path.

I know it doesn't make sense because at design time you can specify a filename and it builds the ImageSource for you. In code you need to create the ImageSource (or derived object, ie: BitmapSource) and load the appropriate image into it.

Edit: Try this, untested (and check my link above):

    public ImageSource GetGlowingImage(string name)
    {
        string fileName = string.Empty;

        switch (name)
        {
            case "Andromeda":
                {
                    fileName = "HeroGlowIcons/64px-Andromeda.gif";
                    break;
                }
        }

        BitmapImage glowIcon = new BitmapImage();


        glowIcon.BeginInit();
        glowIcon.UriSource = new Uri("pack://application:,,,/ApplicationName;component/" + fileName);
        glowIcon.EndInit();

        return glowIcon;
    }