2017-06-05 26 views
0

我有一個關於如何從條目標記/視圖綁定到使用類查看模型的問題。每當我嘗試將數據提交給我的視圖模型類時,我都有一個空值。如何從視圖綁定數據以查看Xamarin中的模型?

下面是視圖的代碼:

Entry Text="{Binding User.UserName, Mode=TwoWay}"/> 
<Entry Text="{Binding User.Password, Mode=TwoWay}"/> 

<Button Text="Login" Command="{Binding LoginCommand}"/> 

下面是視圖模型的代碼(構造部分):

public LoginPageViewModel(IApiService apiService, INavigationService navigationService) 
    { 
     this.apiService = apiService; 
     this.navigationService = navigationService; 
     LoginCommand = new DelegateCommand(Login); 
    } 

在視圖模型,我還一類使用用戶模型的用戶名和密碼:

private Users user; 
    public Users User 
    { 
     get { return user; } 
     set { SetProperty(ref user, value); } 
    } 

這裏是用戶的模型:

public class Users : BindableObject 
{ 
    private string username; 

    public string UserName 
    { 
     get { return username; } 
     set { username = value; } 
    } 

    private string password; 

    public string Password 
    { 
     get { return password; } 
     set { password = value; } 
    } 

} 

每次我嘗試點擊提交按鈕時,當我試圖調試我的代碼時,我得到空值。

private async void Login() 
    { 
     var test = User.UserName; 

     bool success = await apiService.LoginAsync(User); 

謝謝你對我的Xamarin項目的幫助。

+0

當你創建LoginViewModel時,它是否實例化一個新的User實例,還是隻是null? – Jason

+0

@Jason它根本就是空值。 – jololandayan

回答

1

您需要在viewmodel構造函數中創建一個新的User實例。

public LoginPageViewModel(IApiService apiService, INavigationService navigationService) 
    { 
     this.apiService = apiService; 
     this.navigationService = navigationService; 
     LoginCommand = new DelegateCommand(Login); 

     this.User = new Users(); 
    } 
+0

謝謝。你能舉個例子嗎? – jololandayan

+0

謝謝@Jason和@Diego!輝煌! – jololandayan