C# 如何使用 Resources.resx 链接图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12363834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:00:42  来源:igfitidea点击:

How to use Resources.resx to link images

c#.netwpfimageresources

提问by l46kok

I have included an icon file inside my Resources.resx that I'd like to show on a TreeViewItem that is inside a stackpanel.

我在 Resources.resx 中包含了一个图标文件,我想在堆栈面板内的 TreeViewItem 上显示该文件。

1)Can .ico files be used for this purpose? Or does it have to be .bmp or jpg?

1) .ico 文件可以用于此目的吗?还是必须是 .bmp 或 jpg?

2)What do you set the source as in XAML? The following code didn't work for me

2)你在 XAML 中如何设置源?以下代码对我不起作用

<StackPanel Orientation="Horizontal">
    <Image Margin="2" Source="/Resources/Folder_Back.ico" />
    <TextBlock Margin="2" Text="{Binding ProgramName}"
     Foreground="White" FontWeight="Bold"/>
</StackPanel>

采纳答案by Nahum

you can't do that. that worked only in winforms

你不能那样做。仅适用于 winforms

see this post for more info

看到这个帖子了解更多信息

Different way how add image to resources

将图像添加到资源的不同方式

use the method shown in this post

使用这篇文章中显示的方法

WPF image resources

WPF 图片资源

instead

反而

quote:

引用:

If you will use the image in multiple places, then it's worth loading the image data only once into memory and then sharing it between all Imageelements.

如果您将在多个地方使用图像,那么值得将图像数据仅加载一次到内存中,然后在所有Image元素之间共享。

To do this, create a BitmapSourceas a resource somewhere:

为此,请BitmapSource在某处创建一个作为资源:

<BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" />

Then, in your code, use something like:

然后,在您的代码中,使用以下内容:

<Image Source="{StaticResource MyImageSource}" />

In my case, I found that I had to set the Image.pngfile to have a build action of Resourcerather than just Content. This causes the image to be carried within your compiled assembly.

就我而言,我发现我必须将Image.png文件设置为具有构建操作,Resource而不仅仅是Content. 这会导致在编译的程序集中携带图像。

回答by Qorbani

Here is a trick to access image in Resource file:

这是访问资源文件中图像的技巧:

Accessing image from Resource File in XAML markup

从 XAML 标记中的资源文件访问图像

First you need to add reference to project properties like this:

首先,您需要像这样添加对项目属性的引用:

xmlns:properties="clr-namespace:MyProject.Properties"

And then access it via XAML like this:

然后像这样通过 XAML 访问它:

<image source="{Binding Source={x:Static properties:Resources.ImageName}}" />

You can use PNG/JPG/BMP as well as ICO file but everyone recommend PNG.

您可以使用 PNG/JPG/BMP 以及 ICO 文件,但每个人都推荐 PNG。

回答by WhileTrueSleep

to make the solution of Qorbani work add a converter to the Image Source.Binding!

要使 Qorbani 工作的解决方案添加到 Image Source.Binding 的转换器!

XAML - Namespaces

XAML - 命名空间

 xmlns:properties="clr-namespace:YourNameSpace.Properties"
 xmlns:converter="clr-namespace:YourNameSpace.Converter"

Xaml - Resource (UserControl or Window)

Xaml - 资源(用户控件或窗口)

 <UserControl.Resources>
        <ResourceDictionary>
              <converter:BitmapToImageSourceConverter x:Key="BitmapToImageSourceConverter" />
        </ResourceDictionary>
 </UserControl.Resources>

Xaml Code

Xaml 代码

<StackPanel Orientation="Horizontal">
                    <Image Width="32" Height="32" Source="{Binding Source={x:Static properties:Resources.Import}, Converter={StaticResource BitmapToImageSourceConverter}}" Stretch="Fill" />
                    <TextBlock Margin="5" HorizontalAlignment="Center" VerticalAlignment="Center">Import</TextBlock>
</StackPanel>

BitmapToImageSourceConverter.cs

BitmapToImageSourceConverter.cs

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace YourNameSpace
{
    public class BitmapToImageSourceConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var bitmap = value as System.Drawing.Bitmap;
            if (bitmap == null)
                throw new ArgumentNullException("bitmap");

            var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

            var bitmapData = bitmap.LockBits(
                rect,
                ImageLockMode.ReadWrite,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            try
            {
                var size = (rect.Width * rect.Height) * 4;

                return BitmapSource.Create(
                    bitmap.Width,
                    bitmap.Height,
                    bitmap.HorizontalResolution,
                    bitmap.VerticalResolution,
                    PixelFormats.Bgra32,
                    null,
                    bitmapData.Scan0,
                    size,
                    bitmapData.Stride);
            }
            finally
            {
                bitmap.UnlockBits(bitmapData);
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

回答by Dwight

First: Add resources rsx then: add images as images to the resource file and set the image build action to Resource. Now you can access the images like this:

首先:添加资源 rsx 然后:将图像作为图像添加到资源文件中,并将图像构建操作设置为 Resource。现在您可以像这样访问图像:

<Image Source="pack://application:,,,/Resources/image.png"/>

回答by Gy?rgy K?szeg

The accepted answer says it is not possible and the working solution converts GDI+ Bitmaptypes to WPF images. But those conversions are completely unnecessary. The solution is actually really simple:

接受的答案说这是不可能的,工作解决方案将 GDI+Bitmap类型转换为 WPF 图像。但是这些转换完全没有必要。解决方法其实很简单:

  1. When you add image or icon files to a resource file, the designer picks GDI+ types for them by default:
  1. 当您将图像或图标文件添加到资源文件时,设计器默认为它们选择 GDI+ 类型:

enter image description here

在此处输入图片说明

  1. Just open the .resx file in the XML editor (in Solution Explorer right click, Open With...) and change Bitmapand Icontypes to MemoryStream:
  1. 只需在 XML 编辑器中打开 .resx 文件(在解决方案资源管理器中右键单击,打开方式...)并更改BitmapIcon键入MemoryStream
<!--<value>..\Resources\Undo.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>-->
<value>..\Resources\Undo.png;System.IO.MemoryStream</value>

...

<!--<value>..\Resources\Error.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>-->
<value>..\Resources\Error.ico;System.IO.MemoryStream</value>

  1. Save the .resx file. If you now open the designer you can find your resources under the Othermenu.
  1. 保存 .resx 文件。如果您现在打开设计器,您可以在“其他”菜单下找到您的资源。

enter image description here

在此处输入图片说明

Don't bother with 'fixing' Resources.cs. When you save the .resx file it will be automatically regenerated with the correct types. The generated return type will be actually UnmanagedMemoryStreambut don't be confused about that.

不要为“修复”而烦恼Resources.cs。当您保存 .resx 文件时,它将使用正确的类型自动重新生成。生成的返回类型实际上是UnmanagedMemoryStream但不要对此感到困惑。

  1. Usage:
  1. 用法:
public static class WpfImages
{
    public static ImageSource Error { get; } = BitmapFrame.Create(Resources.Error);
    // [...]
}
<Image Source="{x:Static local:WpfImages.Error}"/>