How to get Uri image stored in resources

I have two .png files added to my resources that I need to access their Uri when doing the binding.

My xaml code is as follows:

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

and binding using ImagePath :

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

but

 Properties.Resources.LedGreen 

returns a Bitmap instead of a String containing the Uri of this particular image. I just want to know how to extract this value without the need for an image path destination in the directory that it stores. (Which, frankly, I'm not sure if this is correct, because I could not find a similar situation on the net).

Please let me know if there is even a preferred method for the one I'm trying to use, if available.

+7
c # resources wpf binding xaml
source share
2 answers

In a WPF application, you usually don't save images in Properties/Resources.resx and access them using the Properties.Resources class.

Instead of just adding image files to your visual studio project as regular files, perhaps in a folder called β€œImages” or the like. Then you set their Build Action to Resource , which will be executed in the Properties window. You get there, for example. by right-clicking the image file and select the Properties menu item. Note that the default value for Build Action must be Resource for image files anyway.

In order to access these image resources from code, you would then use the URI package . With the name of the "Images" folder and the image file named "LedGreen.png" above, creating such a URI will look like this:

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

So, you could declare that your property is of type Uri:

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

and install it like this:

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

Finally, your XAML should look like the one below, which relies on inline type conversions from Uri to ImageSource:

 <Grid> <Image Width="10" Source="{Binding Path=ImageUri}" /> </Grid> 
+18
source share

Declare the Properties.Resources.LedGreen property as ImageSource and set it to the Uri location, not to the Bitmap object.

Or, if you insist on saving it as a bitmap, you can get the source by returning Properties.Resources.LedGreen.ImageSource , which will be of type ImageSource .

I would prefer the first approach.

+1
source share

All Articles