Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I change an image source dynamically from code-behind in WPF with an image in Properties.Resources?
    primarykey
    data
    text
    <p>I have a WPF application that needs to provide feedback to the user about an internal state. The design is to have three images, call them Red, Yellow, and Green. One of these images will be displayed at a time depending on the state. Here are the points:</p> <ul> <li>The three images are in Properties.Resources in the code-behind</li> <li>Only one of the images will be shown at a time.</li> <li>The state change comes from a process in code-behind and not from the user.</li> <li>I would like to bind an image control so that I can change the image from code-behind.</li> </ul> <p>I’m assuming I’ll need an image converter to change the JPG image to an image source such as:</p> <hr> <pre><code>[ValueConversion(typeof(System.Drawing.Bitmap), typeof(ImageSource))] public class BitmapToImageSourceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var bmp = value as System.Drawing.Bitmap; if (bmp == null) return null; return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } </code></pre> <hr> <p>I’d prefer to convert the images once during initialization and keep a list of Image sources. I’m also assuming I’ll need a dependency property to bind the control to, but I’m not sure how to set that up with this list of image sources:</p> <hr> <pre><code> // Dependancy Property for the North Image public static readonly DependencyProperty NorthImagePathProperty = DependencyProperty.Register( "NorthImagePath", typeof(ImageSource), typeof(MainWindow), new PropertyMetadata("**Don't know what goes here!!!**")); // Property wrapper for the dependancy property public ImageSource NorthImagePath { get { return (ImageSource)GetValue(NorthImagePathProperty); } set { SetValue(NorthImagePathProperty, value); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload