2015-10-29 42 views
4

我目前面临以下问题:在Xamarin页自定义事件C#

我想,当用户输入有效凭据才能触发一个事件,这样我可以切换网页等。

问题是我因为某种原因无法挂钩事件(虽然我非常肯定它会是一些愚蠢的事情)。

的类触发事件:

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类中添加一个委托,但它没有帮助。

任何人都可以如此友好地指出我什么愚蠢我正在犯的错误?

回答

5

MainPage定义为Xamarin.Forms.Page。这个班级没有名为OnAuthenticated的房产。因此错误。 您需要在该类型的变量LoginPage实例存储,以便将其分配给MainPage能够访问在类中定义的属性和方法之前:

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

非常感谢!虽然绑定MainPage - > LoginPage MainPage = new LoginPage();发出抱怨根视图控制器的错误。 – RVandersteen

+0

我看到你编辑了你的awser,完全像这样。再次感谢 – RVandersteen