C# 将System.Drawing.Icon转换为System.Windows.Controls.Image

C# 将System.Drawing.Icon转换为System.Windows.Controls.Image,c#,wpf,C#,Wpf,我想在图像控制中显示一个图标,我该怎么做呢 System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(@"C:\Users\bgh32648\Desktop\Filename.extension"); Image Img = new Image(); 我想将图标分配给img public static ImageSource ToImageSource(this Icon icon) { ImageSou

我想在图像控制中显示一个图标,我该怎么做呢

System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(@"C:\Users\bgh32648\Desktop\Filename.extension");

Image Img = new Image();
我想将图标分配给img

public static ImageSource ToImageSource(this Icon icon)
{
    ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon(
        icon.Handle,
        Int32Rect.Empty,
        BitmapSizeOptions.FromEmptyOptions());

    return imageSource;
}

然后
image.Source=icon.ToImageSource()

我尝试了您给出的解决方案,但它抛出了一个错误“扩展方法必须在非泛型静态类中定义”公共部分类MainWindow:Window使用静态类扩展助手将扩展方法放在MainWindow之外的静态类中修复了该错误。谢谢@Snake