c# - "Cannot convert string to ImageSource."我该怎么做?

标签 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;
        }
    }

我只是想制作一个事件,根据鼠标进入的位置更改图像。但我无法完成这项工作。

编辑:我在 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/

相关文章:

c# - 如何检查 Azure Active Directory 中的用户是否属于特定组成员身份?

c# - XAML 碰撞检测

html - Bootstrap 响应式旋转木马,具有自定义高度,不会在移动设备、平板电脑上调整大小

c# - "GenerateDepsFile"任务意外失败 : Missing Microsoft. DotNet.PlatformAbstractions

c# - 如何在 C# 中枚举枚举?

c# - 将 WPF Combobox 的 SelectedItem 转换为 Color 会导致异常

wpf - WPF Datagrid -DataGridTemplateColumn选项卡焦点问题

wpf - 无法加载文件或程序集 'Microsoft.Windows.Design.Interaction, Version=4.3.0.0, PublicKeyToken=b03f5f7f11d50a3a'

html - CSS - 居中图像和其下方的文本

javascript - 如何检查是否单击了同一图像或另一图像或图像以外的其他内容