WPF and MVVM: get values ​​from text fields and send them to ViewModel

I try to get the value of two Texboxes (I simulate a login window) when I click a button. The command assigned to the button works correctly, but I don’t know how to get the value of the text fields for the "input".

This is my 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"); } } 

This view:

  <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}"/> 

If someone can help ... I will be infinitely grateful.

+6
source share
1 answer

Typically, you bind TextBox.Text properties to properties in the ViewModel. Thus, the values ​​are stored in the ViewModel, not in the view, and there is no need to get the values.

 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... 

Then in your XAML you will do something like:

 <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"/> 

At this point, LoginCommand can use local properties directly.

+12
source

Source: https://habr.com/ru/post/948484/


All Articles