【发布时间】:2015-12-14 03:53:39
【问题描述】:
我的目标如下:我想将一个文件拖放到我的 WPF 窗口中,它应该在运行时创建一个带有图标图像的按钮。
目前我的代码只是创建一个没有任何图像的按钮。我是 WPF 新手,所以请放轻松!
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);
}
}
}
【问题讨论】:
-
我的回答有帮助吗?
标签: c# wpf xaml attached-properties