Search code examples
c#wpfimagesource

Switch image source between two images


I want to toggle between two images within a list and update their source depending on some condition. But when the second image is updating, I want the first one to keep the last shown image. Basically what is happending here is that both get updated because source is bound to both. How to make it right in an efficient way?

Update: I render a D3DImage and want to overlay two images (like chart axes(backImage) and points(targetImage)). Depending on a condition I change the axes or the points image.

Basically what I have is:

List<Image> imageList = new List<Image>();
imageList.Add(backImage);
imageList.Add(targetImage);

if(condition)
   imageList[0].Source = someSource;
else
   imageList[1].Source = someSource;

Solution

  • You can't do exactly what you're asking... you can't update an Image.Source property and still have that Image display the old image. However, you can easily do this using XAML and Binding to the Image.Source property of each Image:

    Add two properties in your view model or code behind that implement the INotifyPropertyChanged interface:

    // Don't copy this - implement the `INotifyPropertyChanged` interface properly
    public ImageSource ImageSource1 { get; set; } 
    public ImageSource ImageSource2 { get; set; }
    

    Set these properties:

    ImageSource1 = ImageSource2 = someSource;
    

    Now Bind these properties to the Image controls:

    <Image Source="{Binding ImageSource1}" />
    <Image Source="{Binding ImageSource12}" />
    

    Now you can set them to the same image or to different images independently:

    ImageSource2 = anotherSource;