WPF数据绑定失败:
model层的绑定的数据全部失败,ViewModel层可以绑定
先上图:
ErrorMessage是登录按钮下面空白区域要提示的内容
View层
<TextBox Style="{DynamicResource TextUserBoxStyle}" Text="{Binding loginModel.UserName}" FontSize="16" Width="300" Height="35" />
<PasswordBox Style="{DynamicResource TextPasswordBoxStyle}" command:PasswordHelper.Attach="True" command:PasswordHelper.Password="{Binding loginModel.Password}" FontSize="16" Grid.Row="1" Width="300" Height="35"/>
<TextBox Style="{DynamicResource TextVerificationBoxStyle}" Text="{Binding loginModel.ValidationCode}" FontSize="16" Grid.Row="2" Width="300" Height="35"/>
<TextBlock Text="{Binding loginModel.ErrorMessage}" Foreground="Red" Grid.Row="4" TextWrapping="Wrap" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button Content="登 录" Command="{Binding LoginClick}" Grid.Row="3" Width="300" Height="35" Template="{StaticResource LoginButton}" Foreground="White"/>
View.cs
public LoginView()
{
InitializeComponent();
DataContext = new LoginViewModel();
}
ViewModel层
public partial class LoginViewModel : ObservableObject
{
public ICommand closeWindow { get; }
public ICommand LoginClick { get; }
public LoginViewModel()
{
closeWindow = new RelayCommand(DoClose);
LoginClick = new RelayCommand(DoLogin);
}
void DoClose()
{
//关闭窗口(知道如何把View的窗体控件传参到此处吗?我好使用e.close()关闭它 )
}
void DoLogin()
{
LoginModel loginModel = new LoginModel();
if (string.IsNullOrEmpty(loginModel.UserName))
{
loginModel.ErrorMessage = "请输入账号!";
return;
}
if (string.IsNullOrEmpty(loginModel.Password))
{
loginModel.ErrorMessage = "请输入密码!";
return;
}
if (string.IsNullOrEmpty(loginModel.ValidationCode))
{
loginModel.ErrorMessage = "请输入验证码!";
return;
}
}
}
Model层
public class LoginModel:ObservableObject
{
public string userName;
public string UserName
{
get => userName;
set
{
userName = value;
OnPropertyChanged(nameof(UserName));
}
}//用户名输入框绑定源
public string password;
public string Password
{
get => password;
set
{
password = value;
OnPropertyChanged(nameof(Password));
}
}//密码输入框绑定源
public string validationCode;
public string ValidationCode
{
get => validationCode;
set
{
validationCode = value;
OnPropertyChanged(nameof(ValidationCode));
}
}//验证码输入框绑定源
public string ErrorMessage { get; set; }
}
知道的人请指导一下,谢谢