2015-05-09 68 views
0

我的目标是将新创建的学生参数从TextBox添加到List集合中。
据我所知,下面的代码不这样做。将WPF文本框中的值添加到列表

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 

     btnCreateStudent.Click += btnCreateStudent_Click; 
    } 

    private void btnCreateStudent_Click(object sender, RoutedEventArgs e) 
    { 
     Student student = new Student(); 
     student.Name = txtFirstName.Text; 
     student.Surname = txtLastName.Text; 
     student.City = txtCity.Text; 

     student.Students.Add(student); 
     txtFirstName.Text = ""; 
     txtLastName.Text = ""; 
     txtCity.Text = ""; 
    } 

    class Student 
    { 
     private string name; 

     public string Name 
     { 
      get { return name; } 
      set { name = value; } 
     } 
     private string surname; 

     public string Surname 
     { 
      get { return surname; } 
      set { surname = value; } 
     } 
     private string city; 

     public string City 
     { 
      get { return city; } 
      set { city = value; } 
     } 

     public List<Student> Students = new List<Student>(); 
    } 
} 
+0

一个'List'或'ListBox'? –

+0

一个列表。我需要它来存储表单用户输入的数据,以便稍后用户在表单中按下“Prevoius”和“Next”按钮时在TextBox中显示。 – Belkin

回答

2

您是否已将List<Student> Students与前端的ListBox绑定在一起。在WPF中使用数据绑定。只要您更新数据,UI就会自动更新。

这是代码。在XAML:

<DataTemplate x:Key="StudentTemplate"> 

       <TextBlock Text="{Binding Path=Name}"/> 

</DataTemplate> 



<ListBox Name="listBox" ItemsSource="{Binding}" 
      ItemTemplate="{StaticResource StudentTemplate}"/> 

这里是它的教程:

http://www.wpf-tutorial.com/listview-control/listview-data-binding-item-template/

0

您的代码似乎罚款将其添加到列表中。

做一个列表框的标签在你的XAML:

<ListBox Name="studentList"/> 

比你的代码隐藏:

当然,如果你想在列表中添加到一个列表框,你可以轻松地做这样的事情去做
studentList.Items.Add(student); 

事实上,你将不再需要任何的名单都只是初始化学生对象,并填写他们。

相关问题