Search code examples
c#xamarinxamarin.formsdata-binding

Xamarin Forms How to update an image on screen after a variable behind has been set to a different value?


I would like to update the image that is being displayed on my screen after the behind code has changed the ImageSource value. I have tried sing INotifyPropertyChnage but this doesn't seem to work idk if this is just me.

public string ImageSource
{
    get => _ImageSource;
    set
      {
         if (_ImageSource == value)
             return;

           _ImageSource = value;
           PropertyChanged(this, new PropertyChangedEventArgs(nameof(ImageSource)));
       }
 }

This my my GameLoop method which assigns the values

private async Task GameLoop(int maxWordsInCurrentGame)
{
     for (int i = 1; i <= maxWordsInCurrentGame; i++)
     {
          var gameResources = GetSourcesFromConfig(CurrentGame, i, true, true, true, true, true, true, false);
          _ImageSource = gameResources["image"];
          _MediaSource = gameResources["video"];
           await Task.Delay(10000);
      }

   CurrentGame += 1;
   StartGame();
 }

I currently only have it to await 10 seconds to change the image but it doesn't happen.

I'm using DataBinding for my XAML front code

<Image Source="{Binding ImageSource}"
               BackgroundColor="White"
               Grid.Row="1"
               VerticalOptions="Start"
               HeightRequest="75"
               Margin="0, 20, 0, 0"
               Aspect="AspectFill"/>

Thanks for your answers in advance.


Solution

  • So it's the wrong property you are updating:

    public string ImageSource
    {
        get => _ImageSource;
        set
          {
             if (_ImageSource == value)
                 return;
    
               _ImageSource = value;
               PropertyChanged(this, new PropertyChangedEventArgs(nameof(ImageSource)));
           }
     }
    

    You could write the code like that then it would be obvious to update "ImageSource" instead of the "_imageSource".

    string _imageSource
    public string ImageSource
    {
        get => _imageSource;
        set
          {
             if (_imageSource == value)
                 return;
    
               _imageSource = value;
               PropertyChanged(this, new PropertyChangedEventArgs(nameof(_imageSource)));
           }
     }