Meh*_*rad 10 c# wpf resources xaml binding
我有两个.png文件添加到我的资源,我需要在进行绑定时访问他们的Uri.
我的xaml代码如下:
<Grid>
<Image>
<Image.Source>
<BitmapImage DecodePixelWidth="10" UriSource="{Binding Path=ImagePath}"/>
</Image.Source>
</Image>
</Grid>
Run Code Online (Sandbox Code Playgroud)
binding使用ImagePath的代码是:
ImagePath = resultInBinary.StartsWith("1") ? Properties.Resources.LedGreen : Properties.Resources.ledRed;
Run Code Online (Sandbox Code Playgroud)
然而
Properties.Resources.LedGreen
Run Code Online (Sandbox Code Playgroud)
返回一个Bitmap而不是String包含该特定图像的Uri.我只是想知道如何提取该值而无需在存储的目录中寻址图像的路径.(老实说,我不确定这是正确的事情,因为我在网上找不到任何类似的情况).
如果有可用的话我甚至可以选择使用的方法,请告诉我.
Cle*_*ens 27
在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");
Run Code Online (Sandbox Code Playgroud)
所以你可以声明你的属性是Uri类型:
public Uri ImageUri { get; set; } // omitted INotifyPropertyChanged implementation
Run Code Online (Sandbox Code Playgroud)
并设置如下:
ImageUri = resultInBinary.StartsWith("1")
? new Uri("pack://application:,,,/Images/LedGreen.png")
: new Uri("pack://application:,,,/Images/LedRed.png");
Run Code Online (Sandbox Code Playgroud)
最后,您的XAML应如下所示,它依赖于从Uri到ImageSource的内置类型转换:
<Grid>
<Image Width="10" Source="{Binding Path=ImageUri}" />
</Grid>
Run Code Online (Sandbox Code Playgroud)