动态更改XAML图像源?

时间:2011-11-08 01:10:51

标签: c# wpf mvvm

如何在运行时更改XAML中的图像源?现在我让他们指向嵌入式资源URI。在视图模型中,我定义了图像控件,但没有绑定任何东西,我如何在视图中获取这些?

2 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分:0)

  

例如,可以使用imageconverter。   如果将property设置为bind,则可以从converter获取值,然后返回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);
        }
    }

}