Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify a default button in Xamarin.Forms

In Xamarin.Forms, how do you designate a button as the default button for a page?

For example, on UWP the click handler for a DefaultButton should fire when the user presses the Enter key while the page has focus.

like image 294
Edward Brey Avatar asked May 01 '17 17:05

Edward Brey


1 Answers

Assuming you are trying to replicate the behavior as noted in your first comment to Alessandro, you want to declare the Completed field of your Entry control to use the same event handler as your button.

For example, in XAML:

<Entry Placeholder="Enter PIN Here"
       Completed="DefaultButton_Clicked"/>

<Button Text="OK"
        Clicked="DefaultButton_Clicked"/>

Then in your code behind:

void DefaultButton_Clicked(object sender, EventArgs e)
{
    //Do stuff
}

If you are looking to do this all in code behind like you have answered, I suggest doing it this way so you are able to unsubscribe your events. You'll find working with anonymous functions to be more of a pain. You should subscribe and unsubscribe your events in OnAppearing/OnDisappearing.

void DefaultButton_Clicked(object sender, EventArgs e)
{
    if (model.MyCommand.CanExecute(null))
            model.MyCommand.Execute(null);
}

protected override void OnAppearing()
{
    base.OnAppearing();
    foreach (var child in ((StackLayout)Content).Children)
    {
        if (child is Entry entry)
            entry.Completed += DefaultButton_Clicked;
    }
}

protected override void OnDisappearing()
{
    base.OnDisappearing();
    foreach (var child in ((StackLayout)Content).Children)
    {
        if (child is Entry entry)
            entry.Completed -= DefaultButton_Clicked;
    }
}
like image 73
Timothy James Avatar answered Sep 28 '22 10:09

Timothy James