【问题标题】:WPF & MVVM: Get values from textboxes and send it to ViewModelWPF 和 MVVM:从文本框中获取值并将其发送到 ViewModel
【发布时间】:2013-07-01 16:11:17
【问题描述】:

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

这是我的 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}"/>

如果有人可以提供帮助...我将不胜感激。

【问题讨论】:

    标签: wpf mvvm icommand delegatecommand


    【解决方案1】:

    通常,您会将 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”那么我如何将它绑定到视图模型
    • @Debhere 您需要使用 string.Split 或类似方法拆分电子邮件以在 VM 中提取它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多