0

How can image sources in the XAML be changed during runtime? Right now I have them pointing to a embedded resource URI. In the view model I have the image controls defined but not bound to anything, how do I get these on the view?

TheWolf
  • 1,675
  • 4
  • 22
  • 34
  • http://stackoverflow.com/questions/2531539/wpf-databind-image-source-in-mvvm – kenny Nov 08 '11 at 01:24
  • Their solution uses DataTriggers which requires defining all the URIs in the XAML, is there a way which I could bind Image controls from my ViewModel to the View so the View is not concerned with the source of the image? Thanks. – TheWolf Nov 08 '11 at 01:37

2 Answers2

1
       <Image x:Name="UserImage" Source="{Binding MembershipUserViewModel.UserId, Converter={StaticResource _userIdToImageConverter}, UpdateSourceTrigger=Explicit}" Stretch="Fill" />


public class UserIdToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var image = String.Format("{0}/../{1}.jpg",
                  Application.Current.Host.Source,
                  value);

        var bitmapImage = new BitmapImage(new Uri(image)){CreateOptions = BitmapCreateOptions.IgnoreImageCache};
        return bitmapImage;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Leblanc Meneses
  • 3,001
  • 1
  • 23
  • 26
0

For example, it's possible to use imageconverter. If you set property to bind, you can get value from converter and then return BitmapSource to bind.

public sealed class ImageConverter : IValueConverter
{
    internal static class NativeMethods
    {
        [DllImport("gdi32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool DeleteObject(IntPtr hObject);
    }

    public BitmapSource ToBitmapSource(System.Drawing.Bitmap source)
    {
        BitmapSource bitSrc = null;

        var hBitmap = source.GetHbitmap();

        try
        {
            bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
        }
        catch (Win32Exception)
        {
            bitSrc = null;
        }
        finally
        {
            NativeMethods.DeleteObject(hBitmap);
        }

        return bitSrc;
    }

    public object Convert(object value, Type targetType,
                          object parameter, CultureInfo culture)
    {
        // call function to get BitmapSource
        using (Bitmap bitmap = new Bitmap("{image path}"))
        {

           return ToBitmapSource(bitmap);
        }
    }

}

Diainwater
  • 180
  • 1
  • 10