gpt4 book ai didi

c# - 如何获取存储在资源中的图像的 Uri

转载 作者:可可西里 更新时间:2023-11-01 08:54:02 25 4
gpt4 key购买 nike

我有两个 .png 文件添加到我的资源中,我需要在进行绑定(bind)时访问它们的 Uri。

我的xaml代码如下:

<Grid>
<Image>
<Image.Source>
<BitmapImage DecodePixelWidth="10" UriSource="{Binding Path=ImagePath}"/>
</Image.Source>
</Image>
</Grid>

并且使用 ImagePath绑定(bind)代码是:

ImagePath = resultInBinary.StartsWith("1") ? Properties.Resources.LedGreen : Properties.Resources.ledRed;

不过

Properties.Resources.LedGreen

返回一个 Bitmap 而不是包含该特定图像的 Uri 的 String。我只想知道如何提取该值,而无需在存储的目录中寻址图像的路径。 (老实说,我不确定这样做是否正确,因为我在网上找不到任何类似的情况)。

如果有的话,请告诉我是否有比我尝试使用的方法更好的方法。

最佳答案

在 WPF 应用程序中,您通常不会将图像存储在 Properties/Resources.resx 中并通过 Properties.Resources 类访问它们。

相反,您只需将图像文件作为常规文件添加到您的 Visual Studio 项目中,可能位于名为“Images”或类似名称的文件夹中。然后将它们的 Build Action 设置为 Resource,这是在“属性”窗口中完成的。你到了那里,例如通过右键单击图像文件并选择 Properties 菜单项。请注意,对于图像文件,Build Action 的默认值无论如何都应该是 Resource

为了从代码中访问这些图像资源,您将使用 Pack URI .使用上述文件夹名称“Images”和名为“LedGreen.png”的图像文件,创建这样的 URI 如下所示:

var uri = new Uri("pack://application:,,,/Images/LedGreen.png");

所以您也许可以将您的属性声明为 Uri 类型:

public Uri ImageUri { get; set; } // omitted INotifyPropertyChanged implementation

然后这样设置:

ImageUri = resultInBinary.StartsWith("1")
? new Uri("pack://application:,,,/Images/LedGreen.png")
: new Uri("pack://application:,,,/Images/LedRed.png");

最后,您的 XAML 应如下所示,它依赖于从 Uri 到 ImageSource 的内置类型转换:

<Grid>
<Image Width="10" Source="{Binding Path=ImageUri}" />
</Grid>

关于c# - 如何获取存储在资源中的图像的 Uri,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22955317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com