2
votes

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?

2

2 Answers

3
votes

You cannot set both the ItemsSource property and the Items property together. Try simply removing your calls to cbTitle.Items.Clear() which is unnecessary if you are setting the ItemsSource property on the next line anyway.


UPDATE >>>

You only need to set the ItemsSource property once, preferably in XAML:

<ComboBox ItemsSource="{Binding Items}" ... />

Once this is done, you shouldn't set it again. To change the items in the ComboBox, simply change the items in the collection... they are now data bound... this is WPF, not WinForms:

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();
    Items = calledList;
}
1
votes

Thanks Sheridan. I have also discovered that if I do...

ObservableCollection<string> calledList = obj.GetList();
calledList.Clear(); // I have to use this line of code
calledList.ItemsSource = calledList;

This solve my problem. I am not using xaml because it gave me problems. You may remember I opened a thread about combobox when navigating through records. I managed to solve that problem by using for loop. have a look at my other thread, if you wish, here

However this is not the final solution. I am learning wpf and its cud operation so it will be interesting what I will discover