views:

26

answers:

1

Currently, I have this in MainWindow.xaml:

<Image Name="LogoImage" />

And this in MainWindow.xaml.cs:

public ImageSource LogoImageSource { get; set; }

....

var rm = new ResourceManager("Project.Properties.Resources", GetType().Assembly);

var logoBmp = (Bitmap) rm.GetObject("CompanyLogo");
if (logoBmp != null)
{
    var hBitmap = logoBmp.GetHbitmap();
    ImageSource src =
        Imaging.CreateBitmapSourceFromHBitmap(
            hBitmap,
            IntPtr.Zero,
            Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());
            LogoImageSource = src;
}

var logoBinding = new Binding("LogoImageSource");
logoBinding.Source = this;
LogoImage.SetBinding(System.Windows.Controls.Image.SourceProperty, logoBinding);

I do it this way because I like to keep images as embedded resources, so there's not a bunch of random files floating around in the users install dir.

But how can I manage the image binding (the last 3 lines of code) from XAML and not C#?

Or, if anyone has any input on how they manage image resources, please share it with me.

+3  A: 

In WPF, you need to use the compile action of Resource, not Embedded Resource. Then you can access it like you want to.

EDIT

If you have to use Embedded Resources, you could do it with an IValueConverter. You're basically moving the code into a reusable class, but it would look something like this:

public class ImageLoadingConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null || !(value is string)) return null;

        var rm = new ResourceManager("Project.Properties.Resources", GetType().Assembly);

        using (var stream = rm.GetStream((string)value))
        {
            return BitmapFrame.Create(stream);
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

You'd then use it like so:

<lcl:ImageLoadingConverter x:Key="imageLoader" />

...

<Image Source="{Binding Source=LogoImage.png, Converter={StaticResource imageLoader}}" />
Abe Heidebrecht
The whole point of this question is how to use the image with the compile action of Embedded Resource. So, while its good input, it doesn't answer the question.
mkocubinski
Ok, so I edited it to show you a way of doing it if you require an Embedded Resource (I'm assuming a legacy app that is sharing this resource, as in a pure WPF app, there is no reason to do this). As pointed out above, both Embedded Resources and Resources are compiled into the assembly, so if you are only trying to avoid a loose file, I would definitely recommend using the Resource build action.
Abe Heidebrecht