简体   繁体   English

在Xamarin.Forms中以编程方式引发控件事件

[英]Raise control event programmatically in Xamarin.Forms

I have a button defined in XAML: 我在XAML中定义了一个按钮:

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

Is there a possibility to raise the Clicked event programmatically? 是否可以通过编程引发Clicked事件? Of course I could call OnLoginButtonClicked , but I'm interested how the Clicked event itself can be raised. 当然,我可以调用OnLoginButtonClicked ,但是我对如何引发Clicked事件本身很感兴趣。

If you just want to call the Clicked action, you can do this trick: 如果您只想调用Clicked操作,则可以执行以下操作:

    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. 如前所述,首选使用实际方法。

You can call DoSomething by event handler or any other place in your code 您可以通过事件处理程序或代码中的任何其他位置调用DoSomething

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

private void DoSomething()
{
    //Click code here.
}
  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(); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM