2013-07-01 354 views
6

ボタンを押すと、2つのTexbox(ログインウィンドウをシミュレートしています)の値を取得しようとしています。ボタンに割り当てられたコマンドは正しく起動しますが、「ログイン」を行うテキストボックスの値を取得する方法はわかりません。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

これは古い投稿ですが、テキストボックスフィールドに複数のメールアドレスを渡す必要がある場合、どのように同じ機能を達成できますか? textBoxの中で私はこのような "[email protected]、defg @ yahoo.com、test @ gmail.com"のように書くと仮定します。それをどうすればviewmodelにバインドしますか? – Debhere

+0

@Debhere string.Splitを使ってメールを分割する必要がありますVM内で抽出することができます。 –

関連する問題