Binding an image source through a property in wpf

I am trying to display an icon using an image source (.jpg). I create the Icon property in the view model and try to assign it the path to the image, but I do not see the image in the view. I tried to convert the path to the bitmap, but it does not work. Is there something I don't see here?

<StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Path=Name}"/> <Image Source="{Binding Path=Icon}"></Image> </StackPanel> BitmapImage img = new BitmapImage(); img.BeginInit(); img.CacheOption = BitmapCacheOption.OnLoad; img.CreateOptions = BitmapCreateOptions.IgnoreImageCache; img.UriSource = new Uri("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg", UriKind.Absolute); img.EndInit(); Icon = img; 
+7
source share
1 answer

I came across this myself once and although it might not be the best solution, it worked for me.

1. Add images to your project, for example:

  • Create images and icons in your project and add images there.
  • Set image assembly action to Content (copy if new)

2. Create an ImageSource property:

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

(Note: I use a micron gauge to help in binding)

3. Update ImageSource as follows:

  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. Associate the source attribute with the YourImage property:

(you already did it)

+19
source

All Articles