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

Kri*_*ill 7 c# wpf icons

我有一个显示目录的树和另一个显示文件的面板.现在显示的文件没有图标.我所知道的是文件的路径.我喜欢做的是将该文件图标显示在该面板中.我需要输出和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;
Run Code Online (Sandbox Code Playgroud)

从那里我调用我的itme并尝试更改其默认图标:

ImageSource i = GetIcon(f.fullname)
ic.image = i
Run Code Online (Sandbox Code Playgroud)

ic 是列表中的给定项,f.fullname包含此处的路径是图像的获取和设置

        public BitmapImage Image
        {
            get { return (BitmapImage)img.Source; }
            set { img.Source = value; }
        }
Run Code Online (Sandbox Code Playgroud)

它不起作用,这是我试过的许多方法中的一种,它说它不能投射不同的类型.有没有人有办法做到这一点?
我完全迷失了.

SLa*_*aks 4

我假设这img是一个标准Image控件。

您的Image财产属于类型BitmapImage,这是一种特定的类型ImageSourceCreateBitmapSourceFromHIcon返回名为 的内部类的实例InteropBitmap,该实例无法转换为BitmapImage,从而导致错误。

您需要将属性更改为ImageSource(or BitmapSourceCreateBitmapSourceFromHIcon返回并继承ImageSource),如下所示:

public ImageSource Image
{
    get { return img.Source; }
    set { img.Source = value; }
}
Run Code Online (Sandbox Code Playgroud)