testing
testing

Reputation: 20279

Raise control event programmatically in Xamarin.Forms

I have a button defined in XAML:

<Button x:Name="loginButton" Text="Login" Clicked="OnLoginButtonClicked" />

Is there a possibility to raise the Clicked event programmatically? Of course I could call OnLoginButtonClicked, but I'm interested how the Clicked event itself can be raised.

Upvotes: 4

Views: 4302

Answers (3)

MRW
MRW

Reputation: 91

If you just want to call the Clicked action, you can do this trick:

    var b = new Button();

    b.Clicked += (x, y) =>
    {
        //Your method here
    };

    var t = b as IButtonController;

    t.SendClicked(); //This will call the action

It is important to note this is not the right one. As it was mentioned before, calling the actual method is preferred.

Upvotes: 5

pjrki
pjrki

Reputation: 248

  1. Assing a delegate method

    testButton3.TouchUpInside += HandleTouchUpInside;
    
  2. Add the method

    void HandleTouchUpInside (object sender, EventArgs ea)
    {
        new UIAlertView("Touch3", "TouchUpInside handled", null, "OK", null).Show();
    }
    

Upvotes: 0

Yuri S
Yuri S

Reputation: 5370

You can call DoSomething by event handler or any other place in your code

void OnLoginButtonClicked(object sender, EventArgs e)
{
    DoSomething ();
}

private void DoSomething()
{
    //Click code here.
}

Upvotes: 1

Related Questions