2013-07-01 36 views
6

我試圖在按下按鈕時獲取兩個Texboxes的值(我在模擬登錄窗口)。按鈕中分配的命令正確啓動,但我不知道如何獲取文本框的值來執行「登錄」。WPF和MVVM:從文本框中獲取值並將其發送到ViewModel

這是我的ViewModel:

class LoginViewModel : BaseViewModel 
{ 
    public LoginViewModel() 
    { 

    } 

    private DelegateCommand loginCommand; 
    public ICommand LoginCommand 
    { 
     get 
     { 
      if (loginCommand == null) 
       loginCommand = new DelegateCommand(new Action(LoginExecuted), 
           new Func<bool>(LoginCanExecute)); 
       return loginCommand; 
      } 
     } 

    public bool LoginCanExecute() 
    { 
     //Basic strings validation... 
     return true; 
    } 
    public void LoginExecuted() 
    { 
     //Do the validation with the Database. 
     System.Windows.MessageBox.Show("OK"); 
    } 
} 

這是視圖:

<Grid DataContext="{StaticResource LoginViewModel}"> 

      <TextBox x:Name="LoginTxtBox" HorizontalAlignment="Left" Height="23" Margin="34,62,0,0" Width="154" /> 
      <PasswordBox x:Name="PasswordTxtBox" HorizontalAlignment="Left" Height="23" Margin="34,104,0,0" Width="154"/> 
      <Button x:Name="btnAccept" 
      HorizontalAlignment="Left" 
      Margin="34,153,0,0" 
      Width="108" 
      Content="{DynamicResource acceptBtn}" Height="31" BorderThickness="3" 
      Command="{Binding LoginCommand}"/> 

如果有人能幫助我就會...被無限感激。

回答

12

通常,您會將TextBox.Text屬性綁定到ViewModel上的屬性。這樣,值存儲在ViewModel中,而不是視圖中,並且沒有「獲取」所需的值。

class LoginViewModel : BaseViewModel 
{ 
    //... 
    private string userName; 
    public string UserName 
    { 
     get { return this.userName; } 
     set 
     { 
      // Implement with property changed handling for INotifyPropertyChanged 
      if (!string.Equals(this.userName, value)) 
      { 
       this.userName = value; 
       this.RaisePropertyChanged(); // Method to raise the PropertyChanged event in your BaseViewModel class... 
      } 
     } 
    } 

    // Same for Password... 

然後,在你的XAML,你會做這樣的事情:

<TextBox Text="{Binding UserName}" HorizontalAlignment="Left" Height="23" Margin="34,62,0,0" Width="154" /> 
<PasswordBox Text="{Binding Password}" HorizontalAlignment="Left" Height="23" Margin="34,104,0,0" Width="154"/> 

在這一點上,LoginCommand可以直接使用本地屬性。

+0

太好了!!!謝謝你,它完美的作品! –

+0

儘管它是一箇舊帖子,但是如果我需要在文本框字段中傳遞多個電子郵件地址,我如何實現相同的功能?在文本框假設我寫這樣「[email protected],defg @ yahoo.com,測試@ gmail.com」然後我怎麼綁定到viewmodel – Debhere

+0

@debhere你需要拆分電子郵件使用string.Split或類似的在VM中提取它們。 –

相關問題