如何在運行時將數據綁定到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();
}
歡迎SO。請閱讀這個[how-to-ask](http://stackoverflow.com/help/how-to-ask)並遵循那裏的指導原則,用附加信息來完善您的問題,例如代碼和錯誤消息來描述您的編程問題。 – thewaywewere
請提供'EmployeeDbContext'類的定義以及綁定'DataContext'的代碼。 – kennyzx