2017-06-06 29 views
0

我有一個datagrid,每列都有一個組合框作爲標題。每個組合框的源代碼綁定到一個可觀察的字符串集合。由於在設計時數據網格的列數是未知的,因此我通過後面的代碼完成了所有這些工作。WPF:ItemContainerGenerator.Status =未開始

當用戶選擇一個項目時,在每個組合框中,該項目在選擇更改後應該被禁用。所以我試圖做這樣一個循環:

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

問題是,當列上的循環達到第二次迭代,我的代碼引發異常。深入瞭解我的局部變量之後,我注意到ItemContainerGenerator.Status除了第一列中的組合框之外都處於NotStarted狀態。你能幫我解決這個問題嗎?

回答

0

看來我找到了解決方案。我需要添加這段代碼在內部循環:

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

看來問題是,ItemContainerGenerator不產生直到不產生每ComboBoxItem。要做到這一點,你應該誘騙用戶界面相信每個ComboBox至少打開過一次。

如果你知道更好的答案,請讓我知道。