2015-05-09 168 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); 

事實上,你將不再需要任何的名單都只是初始化學生對象,並填寫他們。

相關問題