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

前端 未结 7 1606
南旧
南旧 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:38

    for more if you intent to change the background of a Grid or other Panel that support System.Windows.Media.Brush with a click of a button

    private void btnBackgroundImage_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Filter = "Image Files (*.bmp;*.png;*.jpg;)|*.bmp;*.png;*.jpg";
        dlg.Multiselect = false;
        dlg.RestoreDirectory = true;
    
        if (dlg.ShowDialog() == true)
        {
            txtBackImageName.Text = dlg.FileName;
            _layoutRoot.Background = new System.Windows.Media.ImageBrush(GetImageSource(dlg.FileName));
        }
    }
    
    
    public ImageSource GetImageSource(string filename)
    {
        string _fileName = filename;
    
        BitmapImage glowIcon = new BitmapImage();
    
        glowIcon.BeginInit();
        glowIcon.UriSource = new Uri(_fileName);
        glowIcon.EndInit();
    
        return glowIcon;
    }
    

提交回复
热议问题