Click here to Skip to main content
15,891,316 members

Response to: Loading databound images into a menuitem with hierarchical data template

Revision 2
Hi Peltchag,

I had the same problem and AFAIK this isn't possible for resource dictionaries.

What I ended up with is using a ValueConverter in my DataTemplate.

Make the converter accessible (where local is an alias for the namespace)
XML
<local:menuiconconverter x:key="menuIconConverter" xmlns:x="#unknown" xmlns:local="#unknown" />


And then write in your DataTemplate something like:
XML
<setter property="Icon" value="{Binding ImageSource, Converter={StaticResource menuIconConverter}}" />


And in the namespace referenced by local, this class:
C#
using System;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media.Imaging;

[ValueConversion(typeof(String), typeof(Image))]
public class MenuIconConverter : IValueConverter
{
   #region IValueConverter implementation

   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
   {
      if (value == null)
      {
         return Binding.DoNothing;
      }

      string imageUrl = value.ToString();

      if (string.IsNullOrEmpty(imageUrl))
      {
         return Binding.DoNothing;
      }


      var bmp = new BitmapImage(new Uri(imageUrl, UriKind.RelativeOrAbsolute)) { DecodePixelHeight = 16, DecodePixelWidth = 16 };

      return new Image { Width = 16, Height = 16, Source = bmp, UseLayoutRounding = true, SnapsToDevicePixels = true };
   }

   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
   {
      return Binding.DoNothing;
   }

   #endregion
}


Hope this helps,

Regards,

Thomas.
Posted 10-Sep-12 1:12am by Thomas Duwe.