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

前端 未结 7 1545
南旧
南旧 2021-01-13 11:09
private void HeroMouseEnter(object sender, MouseEventArgs e)
    {
        ((Image)sender).Source = GetGlowingImage(((Image)sender).Name);            
    }

    pub         


        
相关标签:
7条回答
  • 2021-01-13 11:59

    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;
        }
    
    0 讨论(0)
提交回复
热议问题