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

前端 未结 7 1614
南旧
南旧 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:56

    Going by your edit, you are happy to have a static set of images in resources. If that's correct, you can do this:

    
      
    
    

    then load it as:

    public ImageSource GetGlowingImage(string name)
    {
      switch (name)
      {
        case "Andromeda":
          return (ImageSource)FindResource("andromeda64");
        default:
          return null;
      }
    }
    

    FindResource requires you to be in code-behind for something in the visual tree (e.g. an event handler). If this isn't the case, or if you want to be able to load things that aren't in a resource dictionary, see Cory's answer. The advantage of using and reusing resources is that you don't need to create a BitmapImage each time you use it (though in this case the overhead cost of doing so will be insignificant).

提交回复
热议问题