WPF动态添加带图像和样式的按钮

时间:2015-12-14 03:53:40

标签: c# wpf xaml attached-properties

我的目标如下:我想将一个文件拖放到我的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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我已按如下方式修改了您的代码,我创建了Image实例并将其设置为按钮内容。请试试这个。

foreach (String fileName in fileNames)
{
    MessageBox.Show("WindowDrop " + fileName);

    Button newButton = new Button();
    newButton.Width = 100;
    newButton.Height = 50;


    //Craete the Image isntance and set the image to be dispalyed
    Image ButtonPicture = new Image();
    ButtonPicture.BaseUri = fileName;

    //Set it to the button content
    newButton.Content = ButtonPicture;

    AttachedProperties.SetImageSource(newButton,src);
    stack.Children.Add(newButton);
}