I have a piece of code doesn't work properly. If I execute the btnNew once there is no problem. If I execute twice I get a error of...
Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.
Main class
ClassA obj = new ClassA();
private void btnNew_Click(object sender, RoutedEventArgs e)
{
//List strings for clearing and then creating new strings for Title combobox
ObservableCollection<string> calledList = obj.GetList();
cbTitle.Items.Clear();
cbTitle.ItemsSource = calledList;
}
ClassA.cs
private ObservableCollection<string> data = new ObservableCollection<string>();
public ObservableCollection<string> GetList()
{
return data;
}
public void SimpleNew()
{
data.Add("A");
data.Add("B");
}
if I use a if statement in the main class it will eliminate the problem then it will create duplicate strings in the combobox. Then I am asking myself do I need to create a method to handle distinct? I am not sure on this.
This my if statement in the main class
if (cbTitle.Items.Count == 0)
{
ObservableCollection<string> calledList = obj.GetList();
cbTitle.Items.Clear();
cbTitle.ItemsSource = calledList;
}
When I used try/catch it catches error and shows the message. So this is not good either.
So my question is can anyone tell me how to solve this problem?