Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous button events in Xamarin

I'm attempting to use a Xamarin Forms Media Plugin. I am getting tripped up on trying to get my button, in my MainPage.XAML file to call the asynchronous function in my MainPage.Xaml.CS file.

The very first line of the code is giving me issues: takePhoto.Clicked += async (sender, args) =>

"Take photo" is the name of my button in my app.xaml file, but I cant seem to fetch the name of my button in my app.xaml.cs no matter what I try, so i don't know how to call this asynchronous function.

Here is the code the library uses to take a picture with the plugin - this code is in my App.Xaml.CS file:

takePhoto.Clicked += async (sender, args) =>
{
    await CrossMedia.Current.Initialize();

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

    if (file == null)
        return;

    image.Source = ImageSource.FromStream(() =>
    {
        var stream = file.GetStream();
        file.Dispose();
        return stream;
    }); 
};

My button is in the App.Xaml page like so:

<Button ClassId="TakePicture"
         Text="Take Picture"
         Margin="100" 
         HorizontalOptions="CenterAndExpand"
        />

This is probably a simple question. Usually i add the Clicked = callFunction() property in the code snipped above, but i don't know how to do that if the function is asynchronous. I'd be very appreciative for any guidance.

like image 656
izzyk Avatar asked May 11 '26 16:05

izzyk


1 Answers

you're overthinking this - just use the async keyword in the handler signature, not in the XAML

<Button ClassId="TakePicture"
     Clicked="TakePhoto"
     Text="Take Picture"
     Margin="100" 
     HorizontalOptions="CenterAndExpand"
    />

then in the code behind

protected async void TakePhoto(object sender, EventArgs a)
{
  ...
}
like image 66
Jason Avatar answered May 14 '26 08:05

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!