【问题标题】:Custom Events in Xamarin Page c#Xamarin 页面 c# 中的自定义事件
【发布时间】:2015-10-29 14:59:27
【问题描述】:

我目前面临以下问题:

我试图在用户输入有效凭据时触发一个事件,以便我可以切换页面等等。

问题是由于某种原因我无法参与活动(尽管我很确定这会很愚蠢)。

触发事件的类:

namespace B2B
{

    public partial class LoginPage : ContentPage
    {
        public event EventHandler OnAuthenticated;

        public LoginPage ()
        {
            InitializeComponent ();
        }

        void onLogInClicked (object sender, EventArgs e)
        {
            loginActivity.IsRunning = true;

            errorLabel.Text = "";

            RestClient client = new RestClient ("http://url.be/api/");

            var request = new RestRequest ("api/login_check",  Method.POST);
            request.AddParameter("_username", usernameText.Text);
            request.AddParameter("_password", passwordText.Text);

            client.ExecuteAsync<Account>(request, response => {

                Device.BeginInvokeOnMainThread ( () => {
                    loginActivity.IsRunning = false;

                    if(response.StatusCode == HttpStatusCode.OK)
                    {
                        if(OnAuthenticated != null)
                        {
                            OnAuthenticated(this, new EventArgs());
                        }
                    }
                    else if(response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        errorLabel.Text = "Invalid Credentials";
                    }
                });

            });

        }
    }
}

在“主课”中

namespace B2B
{
    public class App : Application
    {
        public App ()
        {
            // The root page of your application
            MainPage = new LoginPage();

            MainPage.OnAuthenticated += new EventHandler (Authenticated);

        }

        static void Authenticated(object source, EventArgs e) {
            Console.WriteLine("Authed");
        }
    }
}

当我尝试构建应用程序时,我得到:

类型“Xamarin.Forms.Page”不包含“OnAuthenticated”的定义,也没有 OnAuthenticated 扩展方法

我尝试在 LoginPage 类的外部添加一个委托,但没有帮助。

谁能指出我犯了什么愚蠢错误?

【问题讨论】:

    标签: c# events xamarin xamarin.forms


    【解决方案1】:

    MainPage 定义为Xamarin.Forms.Page。此类没有名为OnAuthenticated 的属性。因此错误。 您需要先将LoginPage 的实例存储在该类型的变量中,然后再将其分配给MainPage,以便访问该类中定义的属性和方法:

    var loginPage = new LoginPage();
    loginPage.OnAuthenticated += new EventHandler(Authenticated); 
    MainPage = loginPage;
    

    【讨论】:

    • 非常感谢!虽然绑定 MainPage -> LoginPage MainPage = new LoginPage();引发一个抱怨根视图控制器的错误。
    • 我看到你编辑了你的 awser,就这样完美地工作。再次感谢
    猜你喜欢
    • 2016-01-13
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多