如何在运行时在wpf中向Combobox添加项目

时间:2017-06-10 11:16:25

标签: wpf xamarin combobox

如何在运行时将数据绑定到Combobox?我在Combobox中使用模板字段,我尝试在代码隐藏中更新Combobox项目源。但不是以形式更新xamarin我的Combobox。在组合框模板字段中,我想用一个事件名称为cbxDeleteStudent_Click的按钮删除组合框项目。但我无法在后面的代码中找到comboxitem。

请帮帮我。

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);

            }
        }
    }

删除组合框项目

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 个答案:

答案 0 :(得分:0)

看起来用于绑定到ComboBox的ItemSourceList<Student>

使用ObservableCollection(Of T)代替List<T>,当添加,删除项目或刷新整个列表时,ObservableCollection会提供 通知 ComboBox项目已更新,而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);