2011-11-08 4 views
0

런타임 중에 XAML의 이미지 소스를 어떻게 변경할 수 있습니까? 지금은 임베디드 리소스 URI를 가리키고 있습니다. 뷰 모델에서 정의 된 이미지 컨트롤이 있지만 아무 것도 구속되지 않습니다. 어떻게 뷰에 표시합니까?동적으로 변경되는 XAML 이미지 원본?

+0

http://stackoverflow.com/questions/2531539/wpf-databind-image-source-in-mvvm – kenny

+0

이들 솔루션은 모든 URI를 정의 할 필요 DataTriggers를 사용 XAML에서 이미지 컨트롤을 내 ViewModel에서 뷰로 바인딩하여 뷰가 이미지 소스와 관련되지 않도록 할 수있는 방법이 있습니까? 감사. – TheWolf

답변

0

예를 들어 imageconverter를 사용할 수 있습니다. 바인딩 할 속성을 설정하면 변환기에서 값을 가져온 다음 BitmapSource를 반환하여 바인딩 할 수 있습니다.

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); 
     } 
    } 

}

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(); 
    } 
} 
관련 문제