How to reference image resources in XAML?

后端 未结 4 1098
轮回少年
轮回少年 2020-11-28 22:08

I put an Image control on a Window and I would like to display an image that is stored in a project resource file named \"Resources.resx\". The name of the imag

相关标签:
4条回答
  • 2020-11-28 22:29
    1. Add folders to your project and add images to these through "Existing Item".
    2. XAML similar to this: <Image Source="MyRessourceDir\images\addButton.png"/>
    3. F6 (Build)
    0 讨论(0)
  • 2020-11-28 22:36

    If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:

    "pack://application:,,,/Resources/Search.png"
    

    Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:

    ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"
    

    when I have a folder named RibbonImages under Resources folder.

    0 讨论(0)
  • 2020-11-28 22:44

    One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.

    Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:UI="clr-namespace:UI.Images" 
    

    Set your Image source like this:

    <Image Source={Binding {x:Static UI:Resources.Search}} /> where 'Search' is name of the resource.

    0 讨论(0)
  • 2020-11-28 22:52

    If you've got an image in the Icons folder of your project and its build action is "Resource", you can refer to it like this:

    <Image Source="/Icons/play_small.png" />
    

    That's the simplest way to do it. This is the only way I could figure doing it purely from the resource standpoint and no project files:

    var resourceManager = new ResourceManager(typeof (Resources));
    var bitmap = resourceManager.GetObject("Search") as System.Drawing.Bitmap;
    
    var memoryStream = new MemoryStream();
    bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
    memoryStream.Position = 0;
    
    var bitmapImage = new BitmapImage();
    bitmapImage.BeginInit();
    bitmapImage.StreamSource = memoryStream;
    bitmapImage.EndInit();
    
    this.image1.Source = bitmapImage;
    
    0 讨论(0)
提交回复
热议问题