ObjectToImageConverter not working for ManagedContent.Icon

Nov 25, 2010 at 11:25 AM

The ManagedContent.Icon property is specified as an ImageSource type, but in the DocumentPaneMenuItemStyle it uses ObjectToImageConverter.  Looking in ObjectToImageConverter, it doesn't handle an ImageSource properly.  Here's what I'm doing to create an ImageSource and set it to the Icon property:

        protected void SetIconFromBitmap(System.Drawing.Bitmap value)
        {
            IntPtr hBitmap = value.GetHbitmap();
            try
            {
                BitmapSource b = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    hBitmap,
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                Icon = b;
            }
            finally
            {
                DeleteObject(hBitmap);
            }
        }

A BitmapSource is definitely an ImageSource.  However, ObjectToImageConverter fails to render it as an image.  I had to make this modification to the converter to make it work:

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double width = 16.0;
            if (parameter != null &&
                parameter is double)
                width = (double)parameter;

            if (value is string)
            {
                Uri iconUri;
                // try to resolve given value as an absolute URI
                if (Uri.TryCreate(value as String, UriKind.RelativeOrAbsolute, out iconUri))
                {
                    var img = new BitmapImage(iconUri);
                    if (img != null)
                    {
                        return new Image() 
                        {
                            UseLayoutRounding = true,
                            Width = width, 
                            Source = img 
                        };
                    }
                }
            }
            else if (value is BitmapImage)
            {
                var img = value as BitmapImage;
                return new Image()
                {
                    UseLayoutRounding = true,
                    Width = width,
                    Source = new BitmapImage(img.UriSource)
                };
            }
            else if (value is ImageSource)
            {
                var img = value as ImageSource;
                return new Image()
                {
                    UseLayoutRounding = true,
                    Width = width,
                    Source = img 
                };
            }

            return value;
        }

I'm a bit out of date on the version, but it's pretty close to your latest version, which seems to have the same problem.  That last else if block catches my case.