Hi guys I’m working on a MAUI app and I have a problem with the ui not updating every after calling OnPRopertyChanged, here are the details:
When calling a command in the ViewModel from the imageButton in the XAML file (using binding), the command calls a method in the ViewModel that changes the source of the image and then OnPropertyChange is called and the image changes in the UI.
the approach above is not good enough because we are not allowing the user to choose between taking a photo and uploading an existing one.
so the other option is that the imageButton in the XAML file will call an event in the code behind there it will show a popup for choosing whether he wants to upload an existing photo or take a new photo. then the code behind will call the view model to update the new photo.
in this case when we call OnPrpertyChange the changes are not updating in our MAUI app. what are we doing wrong here?
this is the XAML file: the first option I was describing is implemented here with the first ImmageButton and the second approach is implemented in the second ImageButton
<Grid Grid.Row="1"
HeightRequest="100"
ColumnDefinitions=",,," HorizontalOptions="FillAndExpand" >
<Frame CornerRadius="13" BorderColor="#c6c1ea" HasShadow="False" Grid.Column="0" Margin="3" Padding="0">
<ImageButton ClassId="1" Source="{Binding ImageSource1, Mode=TwoWay}" Aspect="AspectFill" Command="{Binding AddPhotoFromGallery_Clicked}" />
</Frame>
<Frame CornerRadius="13" BorderColor="#c6c1ea" HasShadow="False" Grid.Column="1" Margin="3" Padding="0">
<ImageButton ClassId="2" Source="{Binding ImageSource2, Mode=TwoWay}" Aspect="AspectFill" Clicked="AddPhoto_Tapped" />
</Frame>
</Grid>
in the second option, we go through the code behind
private async void AddPhoto_Tapped(object sender, EventArgs e)
{
string choosedOption = await DisplayActionSheet("Choose option:", "Cancel", null, "From Gallery", "Take a photo");
if(choosedOption == "From Gallery")
{
await (BindingContext as AddItemPageViewModel).AddPhotoFromGallery();
}
else if(choosedOption == "Take a photo")
{
await (BindingContext as AddItemPageViewModel).TakeAPhoto();
}
}
this is the ViewModel:
public Command AddPhotoFromGallery_Clicked
=> new Command(async () => await AddPhotoFromGallery());
public async Task AddPhotoFromGallery()
{
var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions { Title = "Please pick a photo" });
if (result != null)
{
var stream = await result.OpenReadAsync();
ImageSource1 = ImageSource.FromStream(() => stream);
OnPropertyChanged(nameof(ImageSource1));
}
}
Edit: This is how the properties are declared:
public ImageSource imageSource1;
public ImageSource ImageSource1
{
get { return imageSource1; }
set
{
imageSource1 = value;
OnPropertyChanged(nameof(ImageSource1));
}
}