How to get a Uri of the image stored in the resour

2019-01-09 11:23发布

问题:

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

My xaml code is as followed:

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

and the binding code using ImagePath is:

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

However

Properties.Resources.LedGreen

returns a Bitmap instead of String containing the Uri of that particular image. I just want to know how to extract that value without a need to address a path of the image in the directory that it's stored. (Which honestly I am not sure is a right thing to do as I couldn't find any similar situation on the net).

Please let me know if there is even a preferred method to the one I am trying to use if available.

回答1:

In a WPF application you would usually not store images in Properties/Resources.resx and access them by means of the Properties.Resources class.

Instead you just add the image files to your Visual Studio project as regular files, perhaps in a folder named "Images" or the like. Then you would set their Build Action to Resource, which is done in the Properties window. You get there e.g. by right-clicking the image file and select the Properties menu item. Note that the default value of the Build Action should be Resource for image files anyways.

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

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

So you could perhaps declare your property to be of type Uri:

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

and set 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 shown below, which relies on built-in type conversion from Uri to ImageSource:

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


回答2:

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

Or if you insist of storing 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.