WPF 和 MVVM : Get values from textboxes and send it to ViewModel

标签 wpf mvvm icommand delegatecommand

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

这是我的 View 模型:

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

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

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

最佳答案

通常,您会绑定(bind) 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可以直接使用本地属性。

关于WPF 和 MVVM : Get values from textboxes and send it to ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17409010/

相关文章:

WPF 通知链实现

c# - Automapper 将 Flags Enum 从 ViewModel 映射到域模型

java - 如何防止 RecyclerView 重新添加项目导致从新 Activity (MVVM) 移回后导致同一列表出现重复

wpf - 知道是否选择了整行或 WPF DataGrid 中的列

c# - WPF 中的命名命令

wpf - 事件具有不兼容的签名 - EventHandler<T>

c# - 完全填充自定义几何形状

c# - 使用自定义矩形裁剪图像

wpf - 如何在 WPF 应用程序中设置 TextBlock 和标签的默认颜色、字体系列和字体大小?

wpf - 自定义附加命令