Home > Enterprise >  How can I check if the Unfocus event for an Entry was triggered by a button Click in Xamarin.Forms?
How can I check if the Unfocus event for an Entry was triggered by a button Click in Xamarin.Forms?

Time:01-13

In my code I need to save the data to my database whenever an Entry looses focus, unless it was triggered by the push of a Button. I notice that in Xamarin, when an Entry is focused and a button is clicked, an Unfocus event is first fired for the Entry and then the Button Focus event and then the Button Clicked event.

I need some way to determine if the Unfocus event for an Entry was fired due to the click of a Button. Is there some way to do this?

CodePudding user response:

"I need some way to determine if the Unfocus event for an Entry was fired due to the click of a Button. Is there some way to do this?"

Not directly. Here is a way to infer it.

Set a flag in the Unfocus event, and start a one-time timer. You’ll have to experiment to decide what time interval works well. My guess is somewhere in range 200 ms to 500 ms.

In Button focus event, clear that flag and/or stop the timer.

If the timer Elapsed event fires, without the button Focus event stopping it (or clearing the flag), then you’ve found an Unfocus not due to Button.

At that time, take the desired action.

CodePudding user response:

You can know if the button is clicked by checking the "ispressed"

Here is my sample code you can refer to:

xmal:

 <ContentPage.Content>
         <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
            <Entry x:Name="myentry" Unfocused="E_UFEvent"/>
            <Button x:Name="mybutton" Clicked="Onbutton_Clicked" Text="Click me"/>

        </StackLayout>
    </ContentPage.Content>

codebehind:

  void E_UFEvent(Object sender, EventArgs e)
        {if (mybutton.IsPressed)
            {
                DisplayAlert("Notice", "Fired after button clicked","ok");
            }
  •  Tags:  
  • Related