Untitled
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Windows.Input; using Newtonsoft.Json; public class RegistrationViewModel : INotifyPropertyChanged { private string _name; private DateTime _dateOfBirth = DateTime.Today; private string _email; private string _password; private string _confirmPassword; public string Name { get => _name; set { _name = value; OnPropertyChanged(nameof(Name)); } } public DateTime DateOfBirth { get => _dateOfBirth; set { _dateOfBirth = value; OnPropertyChanged(nameof(DateOfBirth)); } } public string Email { get => _email; set { _email = value; OnPropertyChanged(nameof(Email)); } } public string Password { get => _password; set { _password = value; OnPropertyChanged(nameof(Password)); } } public string ConfirmPassword { get => _confirmPassword; set { _confirmPassword = value; OnPropertyChanged(nameof(ConfirmPassword)); } } // ICommand for Signup button public ICommand SignupCommand { get; } public RegistrationViewModel() { SignupCommand = new RelayCommand(Signup, CanSignup); } private bool CanSignup() { // Add validation logic here (e.g., check for empty fields, password match) return !string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(Password) && Password == ConfirmPassword; } private void Signup() { var newUser = new User { Name = Name, DateOfBirth = DateOfBirth, Email = Email, Password = Password // In a real app, hash this password! }; SaveUserToJson(newUser); // Optional: Clear input fields or navigate to another window Name = ""; Email = ""; Password = ""; ConfirmPassword = ""; } private void SaveUserToJson(User user) { string jsonFilePath = "users.json"; // Get existing users from the file (if it exists) List<User> users = new List<User>(); if (File.Exists(jsonFilePath)) { string json = File.ReadAllText(jsonFilePath); users = JsonConvert.DeserializeObject<List<User>>(json); } // Add the new user users.Add(user); // Serialize the updated list back to JSON string updatedJson = JsonConvert.SerializeObject(users, Formatting.Indented); File.WriteAllText(jsonFilePath, updatedJson); } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } // Basic RelayCommand implementation (you might have your own) public class RelayCommand : ICommand { private readonly Action _execute; private readonly Func<bool> _canExecute; public RelayCommand(Action execute, Func<bool> canExecute = null) { _execute = execute; _canExecute = canExecute; } public event EventHandler CanExecuteChanged { add => CommandManager.RequerySuggested += value; remove => CommandManager.RequerySuggested -= value; } public bool CanExecute(object parameter) => _canExecute == null || _canExecute(); public void Execute(object parameter) => _execute(); }
Leave a Comment