如何读取所有文本框值(映射到数据库字段)并将它们存储在WPF中的数据库中 - MVVM

时间:2011-04-26 11:08:16

标签: wpf mvvm data-binding

我是WPF和MVVM的新手。经过长时间的发明后,我开始知道如何从数据库中检索数据并将其绑定到itemcontrol / listview / gridview。

但我的问题是我没有得到如何读取一堆文本框值并将其存储为数据库中的新记录。

这是我的示例代码..

查看

<ItemsControl ItemsSource="{Binding AllEmployees}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBox Width="100" Text="{Binding FirstName}" Margin="4"/>
                        <TextBox Width="100" Text="{Binding LastName}" Margin="4"/>
                        <TextBox Width="100" Text="{Binding Age}" Margin="4"/>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
</ItemsControl>
<!-- For new Employee Details -->
<StackPanel>
        <TextBox x:Name="FirstName"/>
        <TextBox x:Name="LastName"/>
        <TextBox x:Name="Age"/>
        <Button Content="New" Command="{Binding NewEmployeeCommand}"/>
 </StackPanel>

我的cs文件是

    public ObservableCollection<DataAccess.Employee> AllEmployees
            {
                get;
                private set;
            }  

    public EmployeeListViewModel(EmployeeRepository employeeRepository)
            {
                if (employeeRepository == null)
                {
                    throw new ArgumentNullException("employeeRepository");
                }

                _employeeRepository = employeeRepository;
                this.AllEmployees = new ObservableCollection<DataAccess.Employee> 
                                    (_employeeRepository.ListAll());
 }  

现在我怎样才能通过阅读这些文本框在数据库中存储新员工名字,姓氏,年龄..

如何编写 NewEmployeeCommand 事件的函数来读取文本框(将文本框映射到数据库中适当的数据文件)并将数据存储在数据库中。

非常感谢!

4 个答案:

答案 0 :(得分:2)

如果您尝试使用MVVM,只需:

  • 创建ViewModel以包含View所需的所有属性
  • 绑定到Xaml中的这些属性

例如:

public class EmployeeListViewModel
{
  public ObservableCollection<Employee> AllEmployees {get;private set;}
  public string FirstName {get;set;}
  public string LastName {get;set;}
  public int? Age {get;set;}  
  public ICommand NewEmployeeCommand {get;set;}

  //You need to connect to this method by using a Delegate/RelayCommand see link below
  public void AddNewEmployee()
  {
    //Add your real code here to actually insert into the db
    var result = InsertEmployeeIntoDatabase(FirstName,LastName,Age);
    //You probably want to add this new employee to the list now ;)
    AllEmployees.Add(result);
    //Now you probably want to reset your fields
    FirstName = null;
    LastName = null;
    Age = null;
  }
}

Click here for an implementation of a delegate command

然后就像这样编辑你的xaml:

<ItemsControl ItemsSource="{Binding AllEmployees}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBox Width="100" Text="{Binding FirstName}" Margin="4"/>
                        <TextBox Width="100" Text="{Binding LastName}" Margin="4"/>
                        <TextBox Width="100" Text="{Binding Age}" Margin="4"/>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
</ItemsControl>
<!-- For new Employee Details -->
<StackPanel>
        <TextBox Text={Binding FirstName}"/>
        <TextBox Text={Binding LastName}"/>
        <TextBox Text={Binding Age}"/>
        <Button Content="New" Command="{Binding NewEmployeeCommand}"/>
</StackPanel>

答案 1 :(得分:1)

您可以在命令参数中传递引用:

<StackPanel>
    <TextBox x:Name="FirstName"/>
    <TextBox x:Name="LastName"/>
    <Button Content="New" Command="{Binding NewEmployeeCommand}">
        <Button.CommandParameter>
            <x:Array Type="{x:Type TextBox}">
                <x:Reference Name="FirstName"/>
                <x:Reference Name="LastName"/>
            </x:Array>
        </Button.CommandParameter>
    </Button>
</StackPanel>

根据您使用的事件类型,您可以使用参数并获取值:

TextBox[] textBoxes = e.Parameter as TextBox[]; //RoutedEvent
TextBox[] textBoxes = parameter as TextBox[]; //If the executed handler provides the parameter

string firstName = textBoxes[0].Text;
string lastName = textBoxes[1].Text;
//create entry; store in DB

通过绑定:

<Button.CommandParameter>
    <local:MyEntry FirstName="{Binding ElementName=FirstName, Path=Text}"
                   LastName="{Binding ElementName=LastName, Path=Text}"/>
</Button.CommandParameter>
MyEntry entry = parameter as MyEntry;
//store in DB

答案 2 :(得分:1)

你没有阅读文本框值。您需要一个NewEmployeeViewModel并将TextBoxes绑定到属性。

编辑:

只需使用INotifyPropertyChanged和您需要的属性创建一个类。

public class NewEmployee : INotifyPropertyChanged 
{
   public string FirstName
   {
     get{return this._firstname;}
     set{this._firstname = value;
         OnPropertyChanged("FirstName");}
   }
   //... other properties
 }

xaml

<StackPanel DataContext={Binding MyNewEmployeeProperty}>
    <TextBox x:Name="FirstName" Text={Binding FirstName}/>
    <TextBox x:Name="LastName" Text={Binding LastName}/>
    <TextBox x:Name="Age" Text={Binding Age}/>
    <Button Content="New" Command="{Binding NewEmployeeCommand}"/>
</StackPanel>

答案 3 :(得分:0)

我得到了正确答案。

我在xaml中的新条目应该是

<StackPanel>
        <TextBox Text={Binding Employee.FirstName}"/>
        <TextBox Text={Binding Employee.LastName}"/>
        <TextBox Text={Binding Employee.Age}"/>
        <Button Content="New" Command="{Binding NewEmployeeCommand}"/>
</StackPanel>

我的cs文件

public class EmployeeListViewModel : INotifyPropertyChanged 
{
  Employee _employee;
  RelayCommand _addNewEmployee;
  EmployeeRepository _employeeRepository;

  public Employee Employee
  {
       get
       {
         return _employee;
       }
       set
       {
          _employee = value;
          OnPropertyChanged("Employee");
        }

  }    

  public void NewEmployeeCommand()
  {
    if(_addNewEmployee == null)
    {
       _addNewEmployee = new RelayCommand( param => NewEmployeeCommandExecute(), 
                                           param => NewEmployeeCommandCanExecute
                                          );
    }
  }

  void NewEmployeeCommandExecute()
  {
         _employeeRepository.Add(Employee); 
         _employeeRepository.Save();
   }

   bool NewEmployeeCommandCanExecute
   {
         get
         {
            return true;
         }
   }
}