Xamarin forms - Should the ViewModel expose events for the View to use ?

BenVutiBenVuti USMember ✭✭

Until now I've been using ViewModels implementing INotifyPropertyChanged as a BindingContext to my Views.
Like that I can change values and small stuff. Nothing too crazy here, but what if I want to display an error, trigger an animation, do something fancy, ...

As I am writing this I realize that the answer to the question is most likely 'yes' but maybe some of you can input something I didn't know or think about.

I currently have this piece of code in my view:

    ContactViewModel context => BindingContext as ContactViewModel;

    private async Task<ImageSource> TakePictureAsync() {
        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) {
            await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
            return null;
        }

        var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions {
            PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
            Directory = "Sample",
            Name = "test.jpg"
        });

        if (file == null) {
            return null;
        }

        return context.ReadFile(file);
    }

The only reason it's there is because of the await DisplayAlert that cannot be called from the ViewModel.

I'd solve that like this :
ViewModel
public Func<string, string, string, Task> OnErrorDisplayAlert { get; internal set; }

View

context.OnErrorDisplayAlert += async (title, display, dismiss) => {
    await DisplayAlert(title, display, dismiss);
};

Would anyone do something different ?
Cheers

Best Answers

  • BenVutiBenVuti US ✭✭
    Accepted Answer

    Thanks for the answer,
    This made me realize that I was missing some info about data binding in MVVM, so I went and found this video that gave me some of the knowledge I was missing https://channel9.msdn.com/Shows/XamarinShow/Introduction-to-MVVM

    But as said in the video, this is an introduction and it doesn't cover advanced binding mechanics. Do you have any articles/videos to recommend on the subject ?

Answers

  • BenVutiBenVuti USMember ✭✭
    Accepted Answer

    Thanks for the answer,
    This made me realize that I was missing some info about data binding in MVVM, so I went and found this video that gave me some of the knowledge I was missing https://channel9.msdn.com/Shows/XamarinShow/Introduction-to-MVVM

    But as said in the video, this is an introduction and it doesn't cover advanced binding mechanics. Do you have any articles/videos to recommend on the subject ?

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭
  • BenVutiBenVuti USMember ✭✭

    Thanks I'll take a look

Sign In or Register to comment.