2013-07-01 2 views
6

단추를 누를 때 두 개의 Texboxes (로그인 창을 시뮬레이트하고 있습니다)의 값을 얻으려고합니다. 버튼에 할당 된 명령이 올바르게 실행되지만 "로그인"을 수행 할 텍스트 상자의 값을 얻는 방법을 모르겠습니다.WPF & MVVM : 텍스트 상자에서 값을 가져 와서 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의 속성에 바인딩합니다. 이 방법은 값이 View가 아니라 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에서 추출하기 위해 유사한. –

관련 문제