wpfvisual-studioxamlimageresource-editor

wpf Image resources and visual studio 2010 resource editor


My motivation for this question is really just to specify an image to be used in a user control via a dependency property for ImageSource. I'm hitting some pain points involving the management, access, and unit testing for this.


Solution

  • No, the resource editor is not a good tool for this.

    In a WPF application the best way is to put all of your images in an "Images" directory and mark each one as a "Resource". Then you can reference them directly in Image controls and elsewhere.

    Here are the precise steps:

    Now you can reference your images easily in XAML:

    <Image Source="Images/MyImage.png" />
    

    Or in code:

    var source = (BitmapSource)Application.LoadComponent(
                   new Uri("Images/MyImage.png", UriKind.Relative));
    

    You can also reference images in external assemblies:

    <Image Source="ReferencedAssembly;v1.0.0.1;component/Images/MyImage.png" />
    

    Which in code would be:

    var source = (BitmapSource)Application.LoadComponent(
                   new Uri("ReferencedAssembly;v1.0.0.1;component/Images/MyImage.png",
                     UriKind.Relative));