title: WPF Add a button with image and style dynamically
body: <p>My objective is as follows: I want to drag drop a file to my WPF window and it should create a button with the icon image at run time.</p>
  
  <p>Currently my code simply creates a button without any image in it. Im new to WPF so please go easy on me!</p>
  
  <pre><code>public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.RegisterAttached("ImageSource", typeof(ImageSource), typeof(AttachedProperties), new UIPropertyMetadata(null));
  
  public static void SetImageSource(DependencyObject d, ImageSource source)
  {
      d.SetValue(ImageSourceProperty, source);
  }
  
  
  private Bitmap GetIconImageFromFile(String filename)
  {
      Bitmap bmp = System.Drawing.Icon.ExtractAssociatedIcon(filename).ToBitmap();
      bmp.Save("test.bmp");
      return bmp;
  }
  
  private BitmapImage GetBitmapImageFromBitmap(Bitmap bitmap)
  {
      BitmapImage bitmapImage = new BitmapImage();
      using (MemoryStream memory = new MemoryStream())
      {
          bitmap.Save(memory, ImageFormat.Png);
          memory.Position = 0;
          memory.Seek(0, SeekOrigin.Begin);
  
          bitmapImage.BeginInit();
          bitmapImage.StreamSource = memory;
          bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
          bitmapImage.EndInit();
      }
  
      return bitmapImage;
  }
  
  private void Window_Drop(object sender, System.Windows.DragEventArgs e)
  {
      if (e.Data.GetDataPresent(DataFormats.FileDrop) == true)
      {
          String[] fileNames = (String[])e.Data.GetData(DataFormats.FileDrop);
  
  
          foreach (String fileName in fileNames)
          {
              MessageBox.Show("WindowDrop " + fileName);
  
              Button newButton = new Button();
              newButton.Width = 100;
              newButton.Height = 50;
              //newButton.Template = (ControlTemplate)TryFindResource("btemp2");
              Bitmap bmp = GetIconImageFromFile(fileName);
              BitmapSource src = GetBitmapImageFromBitmap(bmp);
              AttachedProperties.SetImageSource(newButton,src);
              stack.Children.Add(newButton);
          }
      }
  }
  </code></pre>