Search code examples
c#windows-8windows-runtimebitmapimage

How to set an image source in code-behind inside a library?


I have a class library written in C# for Windows 8 with a custom control and a folder called Images with bunch of images in it. In control template I have an image

<ControlTemplate TargetType="local:MyCustomControl">
    <Grid Background="Transparent">
        <Image x:Name="MyImage"
               Height="{TemplateBinding Height}"
               Width="{TemplateBinding Width}"
               Stretch="Fill" />
               ...
    </Grid>
</ControlTemplate>

I want to set in this control's code-behind one of that images (which are inside this class library) as a source for this image. What I have already tried:

  1. Absolute uri using FrameworkElement.BaseUri with both Do Not Copy and Copy Always property values of images:

    this.MyImage.Source = new BitmapImage(new Uri(this.BaseUri, imagePath)); 
    
  2. Relative uri with both Do Not Copy and Copy Always property values of images:

    this.MyImage.Source = new BitmapImage(new Uri(imagePath, UriKind.Relative));
    
  3. ms-resource uri scheme.

How can I achieve it?


Solution

  • Ok, that escalated quickly. :) Maybe, will be useful for others. The solution is to use assembly name of the library in the path:

    var assemblyName = this.GetType().GetTypeInfo().Assembly.GetName().Name;
    this.MyImage.Source = new BitmapImage(new Uri(this.BaseUri, assemblyName + imagePath));