Как сохранить значения textboxs в MVVM с помощью WPF
я новичок в wpf и mvvm я пытался научиться использовать его сначала мне удалось показать список моего класса сотрудников очень хорошо , но когда я хочу добавить новый ( означает новый сотрудник), он сохраняет новую пустую запись в базе данных, я не знаю, как получить значение из textboxs. я много искал , но не могу понять, в чем моя проблема, так что могу ли я получить какую-либо помощь вот мой код
MY MODEL CLASS public class Employees { #region Employee Members int _id; string _firstname; string _address; string _lastname; string _language; string _dob; string _nationality; string _gender; #endregion #region Members Properties Notify.NotifyUIBase n = new Notify.NotifyUIBase(); public int ID { get { return _id; } set { _id = value; } } public string FirstName { get { return this._firstname; } set { if (value != this._firstname) { this._firstname = value; n.RaisePropertyChanged("FirstName"); } } } public string Address { get { return _address; } set { _address = value; n.RaisePropertyChanged("Address"); } } public string LastName { get { return _lastname; } set { _lastname = value; n.RaisePropertyChanged("LastName"); } } public string Language { get { return _language; } set { _language = value; n.RaisePropertyChanged("Language"); } } public string DOB { get { return _dob; } set { _dob = (value).ToString(); n.RaisePropertyChanged("DOB"); } } public string Nationality { get { return _nationality; } set { _nationality = value; n.RaisePropertyChanged("Nationality"); } } public string Gender { get { return _gender; } set { _gender = value; n.RaisePropertyChanged("Gender"); } } #endregion } MY NOTIFY CLASS public class NotifyUIBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } MY VIEWMODEL public class EditaEmployeesViewModel { #region Constructor public EditaEmployeesViewModel() { // intiales commands NewEmployeeButton = new RelayCommand(OpenNewEmployee); UpdateEmployeeButton = new RelayCommand(UpdateEmployee); DeleteEmployeeButton = new RelayCommand(DeleteEmployee); SaveNewEmployeeButton = new RelayCommand(SaveNewEmployee); } #endregion #region Variables public RelayCommand NewEmployeeButton { get; set; } public RelayCommand UpdateEmployeeButton { get; set; } public RelayCommand DeleteEmployeeButton { get; set; } public RelayCommand SaveNewEmployeeButton { get; set; } private Model.Employees _EmployeeRecord; #endregion public Model.Employees EmployeeRecord { get { if (_EmployeeRecord == null) return _EmployeeRecord = new Model.Employees(); return _EmployeeRecord; } set { _EmployeeRecord = value; new Notify.NotifyUIBase().RaisePropertyChanged("EmployeeRecord"); } } #region Adding New Employee #endregion #region Command Methods void OpenNewEmployee(object parameter) { View.AddUpdateEmployee aue = new View.AddUpdateEmployee(); aue.Show(); } void UpdateEmployee(object parameter) { } void DeleteEmployee(object parameter) { } void SaveNewEmployee(object parameter) { Model.Employees empp = EmployeeRecord; DataAccess.EmplyeeDatabaseLayer.InsertEmployee(empp); } #endregion #region get Employee List public ObservableCollection<Model.Employees> EmployeeList { get { ObservableCollection<Model.Employees> List = new ObservableCollection<Model.Employees>(DataAccess.EmplyeeDatabaseLayer.GetEmployeeFromDataBase()); return List; } } #endregion } MY DATABASE CLASS public class EmplyeeDatabaseLayer { public static List<Model.Employees> GetEmployeeFromDataBase() { string sql = "select * from Employees"; DataTable dt = DBConnections.SelectQuery(sql); var Employee = new List<Model.Employees>(); foreach (DataRow row in dt.Rows) { var obj = new Model.Employees() { ID = (int)row["id"], FirstName = (string)row["FirstName"], LastName = (string)row["LastName"], DOB = (string)row["DOB"], Gender = (string)row["Gender"], Nationality = (string)row["Nationality"], Language = ((string)row["Language"]), Address = (string)row["Address"] }; Employee.Add(obj); } return Employee; } internal static void InsertEmployee(Model.Employees employee) { try { string sql = "insert into Employees ([FirstName],[LastName],[Gender],[DOB],[Language],[Nationality],[Address]) values "; sql += "('" + employee.FirstName + "','" + employee.LastName + "','" + employee.Gender + "',"; sql += "'" + employee.DOB + "','" + employee.Language + "','" + employee.Nationality + "'"; sql += ",'" + employee.Address + "')"; DBConnections.InserQuery(sql); MessageBox.Show("Data Saved Successfully."); } catch (SqlException ex) { throw ex; } finally { } } internal static void UpdateEmployee(Model.Employees employee) { try { string sql = "Update Employees set [FirstName]='" + employee.FirstName + "',[LastName]='" + employee.LastName + "',"; sql += "[Gender] ='" + employee.Gender + "',[DOB]='" + employee.DOB + "',[Language]='" + employee.Language + "',"; sql += "[Nationality]='" + employee.Nationality + "',[Address]='" + employee.Address + "' where [ID]='" + employee.ID + "'"; DBConnections.UpdateQuery(sql); MessageBox.Show("Data Updated Successfully."); } catch (SqlException ex) { throw ex; } finally { } } internal static void DeleteEmployee(Model.Employees employee) { try { string sql = "Delete * from Employees where ID='" + employee.ID + "'"; DBConnections.DeleteQuery(sql); MessageBox.Show("Data Deleted Successfully."); } catch (SqlException ex) { throw ex; } finally { } } } <pre lang="text">MY VIEW ( SHOW EMPLOYEES LIST) <Window x:Class="EditaWPF01.NewTest.View.EmployeePage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:EditaWPF01.NewTest.View" xmlns:vm="clr-namespace:EditaWPF01.NewTest.ViewModel" mc:Ignorable="d" Title="Employees" Height="450" Width="800" WindowStartupLocation="CenterScreen"> <Window.DataContext> <vm:EditaEmployeesViewModel/> </Window.DataContext> <Grid> <GroupBox Header="Employees List" Margin="5"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="27"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <ToolBarTray > <ToolBar > <Button x:Name="tlNewGas" ToolTip="New Gas" VerticalAlignment="Center" Padding="0" Command="{Binding NewEmployeeButton}"> <Image Source=".\Pics\File_20px.png" /> </Button> <Separator/> <Button x:Name="tlUpdateGas" ToolTip="Update Gas" VerticalAlignment="Center" Padding="0" Command="{Binding UpdateEmployeeButton}"> <Image Source=".\Pics\Edit File_20px.png"/> </Button> <Separator/> <Button x:Name="btnDelete" ToolTip="Delete Gas" VerticalAlignment="Center" Padding="0" Content="Delete" Command="{Binding DeleteEmployeeButton}"/> </ToolBar> </ToolBarTray> <DataGrid Grid.Row="1" AutoGenerateColumns="False" ItemsSource="{Binding EmployeeList}" CanUserAddRows="False"> <DataGrid.Columns> <DataGridTextColumn Header="F.Name" Binding="{Binding Path=FirstName}"/> <DataGridTextColumn Header="L.Name" Binding="{Binding LastName}"/> <DataGridTextColumn Header="Address" Binding="{Binding Address}"/> <DataGridTextColumn Header="DOB" Binding="{Binding DOB}"/> <DataGridTextColumn Header="Gender" Binding="{Binding Gender}"/> <DataGridTextColumn Header="Nationality" Binding="{Binding Nationality}"/> <DataGridTextColumn Header="Language" Binding="{Binding Language}"/> </DataGrid.Columns> </DataGrid> </Grid> </GroupBox> </Grid> </Window> MY FORM TO ADD NEW EMPLOYEE <Window x:Class="EditaWPF01.NewTest.View.AddUpdateEmployee" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:EditaWPF01.NewTest.View" xmlns:vm="clr-namespace:EditaWPF01.NewTest.ViewModel" mc:Ignorable="d" Title="Add/Update Employee" Height="450" Width="500" WindowStartupLocation="CenterScreen"> <Window.DataContext> <vm:EditaEmployeesViewModel/> </Window.DataContext> <Grid> <Grid.RowDefinitions> <RowDefinition Height="27"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <ToolBarTray Background="Orange"> <ToolBar Background="Orange"> <Button x:Name="tlNewGas" ToolTip="New Gas" VerticalAlignment="Center" Padding="0" Content="Save" Height="27" Command="{Binding SaveNewEmployeeButton}"/> </ToolBar> </ToolBarTray> <Grid Grid.Row="1"> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="150"/> <ColumnDefinition/> </Grid.ColumnDefinitions> <TextBlock Text="First Name :" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center"/> <TextBox Grid.Row="0" Grid.Column="1" VerticalAlignment="Center" Text="{Binding FirstName, UpdateSourceTrigger=Explicit}"/> <TextBlock Text="Last Name :" Grid.Row="1" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center"/> <TextBox Grid.Row="1" Grid.Column="1" VerticalAlignment="Center" Text="{Binding LastName, UpdateSourceTrigger=Explicit}"/> <TextBlock Text="Address :" Grid.Row="2" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center"/> <TextBox Grid.Row="2" Grid.Column="1" VerticalAlignment="Center" Text="{Binding Address, BindingGroupName=Group1, UpdateSourceTrigger=Explicit}"/> <TextBlock Text="DOB :" Grid.Row="3" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center"/> <TextBox Grid.Row="3" Grid.Column="1" VerticalAlignment="Center" Text="{Binding DOB, BindingGroupName=Group1, UpdateSourceTrigger=Explicit}"/> <TextBlock Text="Language :" Grid.Row="4" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center"/> <TextBox Grid.Row="4" Grid.Column="1" VerticalAlignment="Center" Text="{Binding Language, BindingGroupName=Group1, UpdateSourceTrigger=Explicit}"/> <TextBlock Text="Nationality :" Grid.Row="5" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center"/> <TextBox Grid.Row="5" Grid.Column="1" VerticalAlignment="Center" Text="{Binding Nationality, BindingGroupName=Group1, UpdateSourceTrigger=Explicit}"/> <TextBlock Text="Gender :" Grid.Row="6" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center"/> <TextBox Grid.Row="6" Grid.Column="1" VerticalAlignment="Center" Text="{Binding Gender, UpdateSourceTrigger=Explicit}"/> </Grid> </Grid> </Window>
Что я уже пробовал:
я много искал , чтобы решить свою проблему, но я не могу найти решение, если есть проблема с моим кодом, пожалуйста, покажите мне
Graeme_Grant
Мы здесь не для того, чтобы отлаживать ваш код для вас... Вы пробовали использовать отладчик, чтобы увидеть, где ваша проблема?
Что происходит, когда вы нажимаете кнопку SaveNewEmployeeButton
пуговица? Сохраняются ли данные в базе данных? Как вы обновляете таблицу данных, связанную с сеткой? Содержит ли DataTable новую запись?
Пройдитесь по коду и определите, где находится проблема. Теперь вы знаете, что вам нужно решить, чтобы исправить свою проблему.