Search code examples
c#wpfitemcontainergenerator

WPF: ItemContainerGenerator.Status = not started


I have a datagrid where every column has a combobox as header. Each combobox has its source binded to an observable collection of string. I've made all of this by code behind, since the number of columns of the datagrid are unknown at design time.

When the user choose an item, in each combobox, that item should be disabled after the selection changed. So i tried to do a loop like this:

private void Test_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (vm.myArray == null)
        { vm.myArray = new string[myGrid.Columns.Count]; }
        ComboBox cb = sender as ComboBox;
        DataGridColumnHeader parent = cb.Parent as DataGridColumnHeader;
        int index = parent.Column.DisplayIndex;
        string value = cb.SelectedItem as string;
        vm.mYArray[index] = value;
        foreach(DataGridColumn c in griglia.Columns)
        {
            foreach(string s in vm.myArray)
            {
                if(s != null && s != string.Empty)
                {
                    ComboBox dg = c.Header as ComboBox;
                    for (int i = 0; i < dg.Items.Count; i++)
                    {
                        ComboBoxItem it = (ComboBoxItem)dg.ItemContainerGenerator.ContainerFromIndex(i); 
                        if ((string)it.Content == s)
                            it.IsEnabled = false;
                        else
                            it.IsEnabled = true;
                    }
                }
            }
        }
    }

The problem is that when the loop on the columns reach the second iteration, my code raise an exception. After a deep look into my local variables, i noticed that ItemContainerGenerator.Status is NotStarted everywhere except for the combobox in the first column. Can you provide me an help on how to solve this problem?


Solution

  • It seems that I've found a solution. I needed to add this piece of code in the inner loop:

    if(dg.ItemContainerGenerator.Status == GeneratorStatus.NotStarted)
    {
        dg.IsDropDownOpen = true;
        this.UpdateLayout();
        dg.IsDropDownOpen = false;
    }
    

    It seems the problem was that the ItemContainerGenerator is not generated until every ComboBoxItem is not generated. To do this you should trick the UI to believe that each ComboBox was opened at least once.

    If you know better answer please let me know.