2017-06-10 46 views
0

如何在運行時將數據綁定到Combobox?我在Combobox中使用模板字段,我嘗試更新代碼隱藏中的Combobox項目源。但沒有更新Xamarin我的Combobox的形式。並在組合框模板字段中,我想刪除與事件名稱cbxDeleteStudent_Click按鈕組合框項目。但我在後面的代碼中找不到comboxitem。如何在運行時在wpf中將項添加到組合框中

請幫幫我。

MyCodes:

<ComboBox x:Name="cbxStudents" Width="150" ItemsSource="{Binding}"> 
       <ComboBox.ItemTemplate> 
        <DataTemplate> 
         <DockPanel Width="150"> 
          <Label Content="{Binding StudentId}" x:Name="cbxStudentId"></Label> 
          <Label Content="{Binding StudentName}"></Label> 
          <Button Content="Sil" x:Name="cbxDeleteStudent" HorizontalAlignment="Right" Width="35" 
            CommandParameter="{Binding StudentId}" Click="cbxDeleteStudent_Click"></Button> 
         </DockPanel> 
        </DataTemplate> 
       </ComboBox.ItemTemplate> 
      </ComboBox> 

代碼隱藏

private void btnAddNewStudent_Click(object sender, RoutedEventArgs e) 
    { 
     using (EmployeeDbContext db = new EmployeeDbContext()) 
     { 
      Student newStudent = new Student() 
      { 
       StudentName = txtStudent.Text 
      }; 
      db.Students.Add(newStudent); 

      if (db.SaveChanges() > 0) 
      { 
       MessageBox.Show(string.Format("{0} öğrencisi başarı ile eklenmiştir.", txtStudent.Text), "Bilgi", MessageBoxButton.OK); 
       txtStudent.Text = string.Empty; 
       (cbxStudents.ItemsSource as List<Student>).Add(newStudent); 

      } 
     } 
    } 

進行刪除ComboBox項

private void cbxDeleteStudent_Click(object sender, RoutedEventArgs e) 
    { 
     using (EmployeeDbContext db = new EmployeeDbContext()) 
     { 
      Student selectedStudent = db.Students.Find(int.Parse((sender as Button).CommandParameter.ToString())); 
      db.Students.Remove(selectedStudent); 
      db.SaveChanges(); 
     } 
     ((sender as Button).Parent as DockPanel).Children.Clear(); 

    } 
+1

歡迎SO。請閱讀這個[how-to-ask](http://stackoverflow.com/help/how-to-ask)並遵循那裏的指導原則,用附加信息來完善您的問題,例如代碼和錯誤消息來描述您的編程問題。 – thewaywewere

+0

請提供'EmployeeDbContext'類的定義以及綁定'DataContext'的代碼。 – kennyzx

回答

0

它看起來像用於綁定到ComboBox的ItemSource,是List<Student>

使用ObservableCollection(Of T),而不是List<T>,提供的ObservableCollection 通知時得到補充項目,刪除或當整個列表被刷新,組合框項更新,而List<T>沒有。

然後,您只需要添加/從ObservableCollection中刪除項目,而無需觸摸ComboxBox的Items屬性。

添加

(cbxStudents.ItemsSource as ObservableCollection<Student>).Add(newStudent); 

要刪除

ObservableCollection<Student> students = cbxStudents.ItemsSource as ObservableCollection<Student>; 
int studentId = int.Parse((sender as Button).CommandParameter.ToString()); 
Student selectedStudent = students.SingleOrDefault(s => s.StudentId == studentId); 
students.Remove(selectedStudent); 
+0

感謝您的完美解答。 –

相關問題