【问题标题】:WPF Add a button with image and style dynamicallyWPF动态添加带有图像和样式的按钮
【发布时间】: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


【解决方案1】:

我已将您的代码修改如下,我创建了 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);
}

【讨论】:

  • 您好,它有效。现在我想为按钮添加样式。这种风格只是在边框中有一个图像。我想将此样式应用于按钮。然后,我想让图像的源成为我的位图
猜你喜欢
  • 2017-10-08
  • 1970-01-01
  • 1970-01-01
  • 2013-07-31
  • 2016-11-03
  • 2011-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多