WPF MVVM模式的登录界面及代码
时间: 2023-12-06 11:05:48 浏览: 101
WPF MVVM模式完整实列
以下是一个简单的WPF MVVM模式的登录界面及代码:
XAML代码:
```xml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
Title="Login" Height="250" Width="350">
<Window.DataContext>
<local:LoginViewModel />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Username:"/>
<TextBox Grid.Row="0" Grid.Column="1" Width="200" Margin="5" Text="{Binding Username}" />
<Label Grid.Row="1" Grid.Column="0" Content="Password:"/>
<PasswordBox Grid.Row="1" Grid.Column="1" Width="200" Margin="5" Password="{Binding Password}" />
<Button Grid.Row="2" Grid.Column="1" Width="100" Margin="5" Content="Login" Command="{Binding LoginCommand}" IsDefault="True"/>
<Label Grid.Row="3" Grid.Column="1" Content="{Binding ErrorMessage}" Foreground="Red" HorizontalAlignment="Center"/>
<CheckBox Grid.Row="4" Grid.Column="1" Content="Remember Me" Margin="5" IsChecked="{Binding RememberMe}"/>
</Grid>
</Window>
```
ViewModel代码:
```csharp
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
namespace WpfApp1
{
public class LoginViewModel : INotifyPropertyChanged
{
private string _username;
private string _password;
private bool _rememberMe;
private string _errorMessage;
public string Username
{
get { return _username; }
set { _username = value; OnPropertyChanged(); }
}
public string Password
{
get { return _password; }
set { _password = value; OnPropertyChanged(); }
}
public bool RememberMe
{
get { return _rememberMe; }
set { _rememberMe = value; OnPropertyChanged(); }
}
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; OnPropertyChanged(); }
}
public ICommand LoginCommand { get; set; }
public LoginViewModel()
{
LoginCommand = new RelayCommand(Login, CanLogin);
}
private bool CanLogin()
{
return !string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password);
}
private void Login()
{
if (Username == "admin" && Password == "password")
{
if (RememberMe)
{
// Save login information to file or database
}
MessageBox.Show("Login successful!");
}
else
{
ErrorMessage = "Invalid username or password";
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
```
其中,`RelayCommand`是一个实现了`ICommand`接口的自定义命令类,用于绑定按钮的点击事件。你可以在网上找到相关实现代码。
阅读全文