WPF和MVVM:从文本框获取值并将其发送到ViewModel

10

我正在尝试在按下按钮时获取两个文本框的值(模拟登录窗口)。按钮中分配的命令被正确触发,但我不知道如何获取文本框的值以进行“登录”。

这是我的视图模型:

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

如果有人能帮忙...我将无限感激。

1个回答

18

通常情况下,你会将TextBox.Text属性绑定到ViewModel上的属性。这样,值将存储在ViewModel中而不是View中,因此不需要"获取"值。

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 可以直接使用本地属性。


虽然这是一个旧帖子,但如果我需要在文本框字段中传递多个电子邮件地址,该如何实现相同的功能呢?比如,在文本框中我写下了这样的内容:“abcd@gmail.com, defg@yahoo.com,test@gmail.com”,那么我该如何将其绑定到ViewModel? - Debhere
1
@Debhere 你需要使用string.Split或类似的方法来拆分电子邮件,以在VM中提取它们。 - Reed Copsey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接