从给定路径加载图标以在WPF窗口中显示

7

我有一个树形结构的控件,显示了目录,另一个面板显示文件。 目前,所显示的文件没有图标。 我只知道文件的路径。 我希望在该面板中显示该文件的图标。 我需要输出为 Image.source。 目前我的代码如下:

    private ImageSource GetIcon(string filename)
    {
        System.Drawing.Icon extractedIcon = System.Drawing.Icon.ExtractAssociatedIcon(filename);
        ImageSource imgs;

        using (System.Drawing.Icon i = System.Drawing.Icon.FromHandle(extractedIcon.ToBitmap().GetHicon()))
            {
                imgs = Imaging.CreateBitmapSourceFromHIcon(
                                        i.Handle,
                                        new Int32Rect(0, 0, 16, 16),
                                        BitmapSizeOptions.FromEmptyOptions());
            }

        return imgs;

接着,我调用我的itme并尝试使用以下方法更改其默认图标:

ImageSource i = GetIcon(f.fullname)
ic.image = i

ic 是给定的列表项,f.fullname 包含路径。以下是获取和设置图像的代码:

        public BitmapImage Image
        {
            get { return (BitmapImage)img.Source; }
            set { img.Source = value; }
        }

它不起作用,这是我尝试的许多方法之一,它说无法转换不同类型。有人知道如何解决吗?
我完全迷失了。

1个回答

4
我假设img是一个标准的Image控件。
你的Image属性是BitmapImage类型,它是一种特殊的ImageSourceCreateBitmapSourceFromHIcon返回一个名为InteropBitmap的内部类的实例,无法转换为BitmapImage,导致错误。
你需要将属性更改为ImageSource(或BitmapSource,它由CreateBitmapSourceFromHIcon返回,并继承了ImageSource),像这样:
public ImageSource Image
{
    get { return img.Source; }
    set { img.Source = value; }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接