如何使用WPF在MVVM中保存文本框值 [英] How to save the textboxs values in MVVM using WPF

查看:115
本文介绍了如何使用WPF在MVVM中保存文本框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是wpf和mvvm的新手我试图学习使用它,我首先成功地展示了我的员工类列表非常好但是当我想添加一个新员工(意味着新员工)时它会保存一个新的空记录在数据库中,我不知道如何从文本框中获取值。我搜索了很多,但无法达到我的问题,所以我可以得到任何帮助,这是我的代码

i am new in wpf and mvvm i tried to learn to use it first i successes to show a list of my employee class very good but when i want to add a new one ( means a new employee ) it saves an new empty record in the database , i do not know how to get the value from the textboxs. i searched a lot but cannot reach what's my problem , so can i get any help here is my code

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>





我尝试过:



i搜索了很多来解决我的问题,但我找不到解决方案,如果我的代码有问题请告诉我



What I have tried:

i searched a lot to solve my problem but i can not find a solution , if there is a problem with my code please show me

推荐答案

因为我无法调试您的源代码。但请考虑以下几点



1.您正在Employees类中创建NotifyBase对象,我认为这是错误的。您需要从INotifyPropertyChanged接口实现Employees类到适当的NotifyChange到/从UI。在你的情况下从NotifyUIBase派生Employee类(已经实现了NotifyPropertyChanged)。



2.对EditaEmployeeViewModel做同样的事情。派生自NotifyUIBase。

3.通常对于textBox,UpdateSourceTrigger设置为PropertyChanged。因为您希望在文本框中丢失焦点后立即更新VM。 (当焦点丢失时调用TextBox PropertyChange)。确保UpdateSourceTrigger = explicit对你有用
As I cannot debug your source code. But consider following points

1. You are creating NotifyBase object in Employees class, which I think is wrong. You need to implement Employees class from INotifyPropertyChanged interface to properly NotifyChange to/from UI. In your case derive Employee class from NotifyUIBase (which already implements NotifyPropertyChanged).

2. Do the same with EditaEmployeeViewModel. derive from NotifyUIBase.
3. Normally for textBox UpdateSourceTrigger is set as PropertyChanged. Because you want to update your VM as soon as you lost focus from textbox. (TextBox PropertyChange is invoked when focus is lost). Make sure UpdateSourceTrigger = explicit is wrking for you


这篇关于如何使用WPF在MVVM中保存文本框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆