Ser*_*pia 5 c# wpf image mouseevent
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我只是想根据鼠标输入的位置创建一个更改图像的事件.但我无法做到这一点.
编辑:我在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;
}
}
Run Code Online (Sandbox Code Playgroud)
在您的GetGlowingImage()方法中,您需要生成一个新的ImageSource
此链接可能有所帮助:在代码中设置WPF图像源
编辑:
看到这里的区别是,在WindowsForms代码中,您有Properties.Resources._64px_Andromedahero ___ copia是包含图像数据的Image变量的名称.在您的WPF代码中,字符串"filename ...."不是图像或图像源,它只是表示文件路径的字符串.您需要使用该路径加载图像文件.
我知道它没有意义,因为在设计时你可以指定一个文件名并为你构建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;
}
Run Code Online (Sandbox Code Playgroud)