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;
}
}
我只是想制作一个事件,根据鼠标进入的位置更改图像。但我无法完成这项工作。
编辑:我在 Windows 窗体中执行此操作,它 100% 像我希望的那样工作。我如何在 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;
}
}
最佳答案
在您的 GetGlowingImage()
方法中,您需要生成一个新的 ImageSource
此链接可能有帮助:Setting WPF image source in code
编辑:
这里的不同之处在于,在 WindowsForms 代码中,您拥有 Properties.Resources._64px_Andromedahero___copia 是包含图像数据的图像变量的名称。在您的 WPF 代码中,字符串“文件名...”不是图像或图像源,它只是表示文件路径的字符串。您需要使用该路径加载图像文件。
我知道这没有意义,因为在设计时您可以指定一个文件名,它会为您构建 ImageSource。在代码中,您需要创建 ImageSource(或派生对象,即:BitmapSource)并将适当的图像加载到其中。
编辑:试试这个,未经测试(并检查我上面的链接):
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;
}
关于c# - "Cannot convert string to ImageSource."我该怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1904956/