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

后端 未结 2 1312
日久生厌
日久生厌 2020-11-27 20:26

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:



        
相关标签:
2条回答
  • 2020-11-27 21:11

    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>
    
    0 讨论(0)
  • 2020-11-27 21:12

    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.

    0 讨论(0)
提交回复
热议问题