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

后端 未结 2 1327
日久生厌
日久生厌 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:

    
        
    
    

提交回复
热议问题