2011-11-08 124 views
0

運行期間XAML中的圖像源如何更改?現在我讓他們指向一個嵌入式資源URI。在視圖模型中,我定義了圖像控件但沒有綁定任何東西,我如何在視圖中獲取這些控件?動態更改XAML圖像源?

+0

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

+0

他們的解決方案使用其要求限定的所有URI DataTriggers在XAML中,有沒有一種方法可以將我的ViewModel中的Image控件綁定到視圖,以便View不關心圖像的來源?謝謝。 – 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(); 
    } 
}