Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取存储在资源中的图像的Uri_C#_Wpf_Xaml_Binding_Resources - Fatal编程技术网

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

C# 如何获取存储在资源中的图像的Uri,c#,wpf,xaml,binding,resources,C#,Wpf,Xaml,Binding,Resources,我有两个.png文件添加到我的资源中,我需要在绑定时访问它们的Uri 我的xaml代码如下: <Grid> <Image> <Image.Source> <BitmapImage DecodePixelWidth="10" UriSource="{Binding Path=ImagePath}"/> </Image.Source> </Image> </Grid> 然而

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

我的
xaml
代码如下:

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

Properties.Resources.LedGreen
返回包含特定图像Uri的
位图
,而不是
字符串
。 我只想知道如何提取该值,而不需要在存储该值的目录中寻址该图像的路径。(老实说,我不确定这样做是否正确,因为我在网上找不到类似的情况)


请让我知道是否有比我尝试使用的方法更好的方法(如果可用)。

属性.Resources.LedGreen
属性声明为
ImageSource
,并将其设置为Uri位置,而不是位图对象

或者,如果您坚持将其存储为位图,则可以通过返回
Properties.Resources.LedGreen.ImageSource
类型来获取源代码


我更喜欢第一种方法。

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

相反,您只需将图像文件作为常规文件添加到VisualStudio项目中,可能位于名为“Images”或类似文件夹中。然后您可以将他们的
构建操作
设置为
资源
,这是在属性窗口中完成的。例如,右键单击图像文件并选择
Properties
菜单项即可到达该位置。请注意,
生成操作
的默认值无论如何都应该是图像文件的
资源

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

var uri = new Uri("pack://application:,,,/Images/LedGreen.png");
ImageUri = resultInBinary.StartsWith("1")
         ? new Uri("pack://application:,,,/Images/LedGreen.png")
         : new Uri("pack://application:,,,/Images/LedRed.png");
因此,您可以将您的属性声明为Uri类型:

public Uri ImageUri { get; set; } // omitted INotifyPropertyChanged implementation
设置如下:

var uri = new Uri("pack://application:,,,/Images/LedGreen.png");
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>


感谢您的描述性回答,更重要的是,感谢您对正确操作方法的建议。我已经按照您建议的方式实现了我的解决方案,但是我想知道我是否需要将这些图像与我要交给其他团队的可执行文件一起携带和保存?由于这是一个相当简单的项目,我不打算为它制作安装程序。不,
资源
构建操作将图像文件添加到程序集。因此它们包含在可执行文件中。