0

I tried different methods from existing posts but I am not able to update an image into the Image control. If I execute the code below directly from the view cs, it works fine (so don't pay attention to .Convert method, so the format is ok). However, I am not reaching the image update from another class.

The issue seems to be the OnPropertyChanged event, where the code executes the 'set' of the _displayedImage object properly, but when the 'get' is triggered, the bitmapImage has errors... Why if is the same object?

ViewModel:

//Image displayed
private BitmapImage _displayedImage;
public BitmapImage DisplayedImage
{
    get { 
        return _displayedImage; }

    set {
        _displayedImage = value;
        OnPropertyChanged("DisplayedImage");
    }
}

Xaml:

<Image x:Name="ImageViewer" Source="{Binding DisplayedImage}" HorizontalAlignment="Center" VerticalAlignment="Top" Stretch="Fill"/>

Code to update image:

Bitmap bmp= new Bitmap(@"C:\test.jpg");
    
RunVM.DisplayedImage = Utilities.Instance.Convert(bmp);

Update 1:

When the set is triggered, _displayedImage has the proper content:

enter image description here

After that, when the event is triggered, _displayedImage has errors: enter image description here

Jaume
  • 3,672
  • 19
  • 60
  • 119
  • Is `RunVM` assigned to the `DataContext` of the view? Do you observe any data binding error messages in the Output Window in Visual Studio when you debug the application? As a note, `Mode=TwoWay` on the Source Binding is pointless. – Clemens Jul 27 '22 at 08:39
  • yes @Clemens, I have another textbox bindings for example of the same DataContext working fine from the same method or class – Jaume Jul 27 '22 at 08:40
  • What you are showing here should work. The problem must be somewhere in the code parts you are not showing. As a note, the `if` statement in the property setter does not make much sense if it does not also contain the OnPropertyChanged call. Add some parentheses, or remove the if statement. Firing PropertyChanged for a property that has not actually changed doesn't hurt. – Clemens Jul 27 '22 at 08:54
  • Removed the if clause and get more info. Please see the update – Jaume Jul 27 '22 at 11:07
  • Are you setting the DisplayedImage property on a different thread than the UI thread? – Clemens Jul 27 '22 at 11:12
  • yes I do... same way that I changed the properties for other controls in the UI – Jaume Jul 27 '22 at 11:30
  • 1
    The difference is that the value of this property is a DispatcherObject, which is by definition not accessible across multiple Threads. Since it is also a Freezable, you can call its Freeze method to make it cross-thread accessible. Make sure your Convert method calls Freeze on the BitmapImage before returning. – Clemens Jul 27 '22 at 11:37
  • ok understood. Implemented and working. Thanks! – Jaume Jul 27 '22 at 12:45

0 Answers0