I tried to add item dynamically to ComboBox.
but it throw the exeption “Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead”.

namespace Trainning
{
public partial class ComboBox : Window
{
int intex_count;
public ComboBox()
{
this.InitializeComponent();
add_items();
}
public List<object> add_items()
{
List<object> items = new List<object>();
items.Add("chandru");
items.Add(83);
com_add_remove.ItemsSource = items;
com_add_remove.SelectedIndex = 0;
return items;
}
private void btn_add_Click(object sender, RoutedEventArgs e)
{
com_add_remove.Items.Add(txt_item.Text);
intex_count = com_add_remove.Items.Count;
com_add_remove.SelectedIndex = intex_count - 1;
}
Your problem is that when you use
ItemsSource, you can’t also add items manually to the same component. So you have to either useItemsSouceor add and remove items manually.I would go with
ItemsSource, and to the following change:replace:
with:
That means you have to add items as a class variable instead of just a local variable inside the add_items method so that you can reference it from
btn_add_Clickas well.Your other option is to change the add_items method so add items istead of using
ItemsSource:replace:
with: