samedi 27 juin 2015

set image source in wpf

I try to follow code to set image source in WPF, when i want to delete old and set new image, rightly but image not refresh and show old picture. why?

Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

string subpath = "UserProfile";
Directory.CreateDirectory(subpath);


// Set filter for file extension and default file extension 
dlg.DefaultExt = ".jpg";
dlg.Filter = "jpeg Files (*.jpg)|*.jpg";
// Display OpenFileDialog by calling ShowDialog method 
if (dlg.ShowDialog() == true)
{
       string fileName = "pic" + txtEmployeeID.Text + ".jpg";
       string newPath = "\\" + subpath + "\\" + fileName;

       if (File.Exists(Directory.GetCurrentDirectory() + "\\" + newPath))
       {
            imgUser.Source = null;
            File.Delete(Directory.GetCurrentDirectory() + newPath);
       }

  File.Copy(dlg.FileName.ToString(), Directory.GetCurrentDirectory() + "\\" + newPath);

       ImageSource imageSrc = BitmapFromUri(new Uri(Directory.GetCurrentDirectory() + newPath));
       imgUser.Source = imageSrc;

}



 public static ImageSource BitmapFromUri(Uri source)
 {
      var bitmap = new BitmapImage();
      bitmap.BeginInit();
      bitmap.UriSource = source;
      bitmap.CacheOption = BitmapCacheOption.OnLoad;
      bitmap.EndInit();
      return bitmap;
 }

Aucun commentaire:

Enregistrer un commentaire