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

标签 c# wpf xaml binding resources

我有两个 .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/

相关文章:

c# - 在本地窗口中更改 T 类型 int

wpf - WPF 应用程序框架 (WAF) 中的 MVVM Collection View

c# - 从代码背后在Viewmodel中设置属性

c# - 从 Child UserControl 更改 MainWindow 中 TabControl 的 SelectedIndex

c# - WPF MVVM : How to close a window

c# - 对于简单函数来说,静态相对于非静态的任何优势

c# - 动态加载和激活数据集(vuforia 和 unity)

c# - zedgraphweb 的局限性

WPF 渲染线程挂起

c# - WPF webbrowser 的 LoadCompleted 事件