Binding image source through property in wpf

后端 未结 1 845
面向向阳花
面向向阳花 2020-12-11 05:10

I am trying to display an icon using an image source(.jpg). I create a Icon property in view model and try to assign it the path of the image but I do not see any image in t

相关标签:
1条回答
  • 2020-12-11 05:29

    I ran into this myself once and, though maybe not the best solution, the following worked for me.

    1. Add the images to your project, for example:

    • Create a folder images/icons to your project and add the images there.
    • Set build action of images to Content (copy if newer)

    2. Create an ImageSource property:

        public ImageSource YourImage
        {
            get { return _yourImage; }
            set 
            { 
                _yourImage = value;
                NotifyOfPropertyChange(() => YourImage);
            }
        }
    

    (Note: I use caliburn micro to assist in binding)

    3. Update the the ImageSource like this:

                if(!string.IsNullOrEmpty("TheImageYouWantToShow"))
                {
                    var yourImage = new BitmapImage(new Uri(String.Format("Images/Icons/{0}.jpg", TheImageYouWantToShow), UriKind.Relative));
                    yourImage.Freeze(); // -> to prevent error: "Must create DependencySource on same Thread as the DependencyObject"
                    YourImage = yourImage;
                }
                else
                {
                    YourImage = null;   
                }
    

    4. Bind source attribute to YourImage property:

    (you already did this)

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