2010-10-26 68 views
2

我已將組合框綁定到string []。 我還沒有清除組合框項目。但我想測量我的下落物品。 如何在運行時獲得組合框中項目的寬度。我需要這個來管理我的組合的寬度。如果要做到這一點,你不知道是否已產生所有ComboBoxItems,那麼你可以使用此代碼獲取ComboBoxItem的寬度

foreach(var item in MyComboBox.Items){ 

    double width = item.ActualWidth; 

} 

回答

5

+0

完美。你知道這個訣竅在哪裏?我試了兩天 – 2010-10-26 16:43:06

+0

是的,我也花了一段時間。我有點一片混亂。 ItemContainerGenerator.StatusChanged是非常常見的,但在這種情況下,對於大約1%的情況來說是不夠的,所以我必須添加DropDownOpened事件。擴大和崩潰的方式是通過谷歌:-) – 2010-10-26 21:09:15

+0

這將是一個很好的作爲附加屬性,或只是一個子分類的組合框的實現 – JJS 2013-11-03 21:17:29

0

試試這個功能。它將在後面的代碼中展開ComboBox,並且當它中的所有ComboBoxItem被加載時,測量它們的大小,然後關閉ComboBox。

的IExpandCollapseProvider是UIAutomationProvider

public void SetComboBoxWidthFromItems() 
{ 
    double comboBoxWidth = c_comboBox.DesiredSize.Width; 

    // Create the peer and provider to expand the c_comboBox in code behind. 
    ComboBoxAutomationPeer peer = new ComboBoxAutomationPeer(c_comboBox); 
    IExpandCollapseProvider provider = (IExpandCollapseProvider)peer.GetPattern(PatternInterface.ExpandCollapse); 
    EventHandler eventHandler = null; 
    eventHandler = new EventHandler(delegate 
    { 
     if (c_comboBox.IsDropDownOpen && 
      c_comboBox.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated) 
     { 
      double width = 0; 
      foreach (var item in c_comboBox.Items) 
      { 
       ComboBoxItem comboBoxItem = c_comboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem; 
       comboBoxItem.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); 
       if (comboBoxItem.DesiredSize.Width > width) 
       { 
        width = comboBoxItem.DesiredSize.Width; 
       } 
      } 
      c_comboBox.Width = comboBoxWidth + width; 
      // Remove the event handler. 
      c_comboBox.ItemContainerGenerator.StatusChanged -= eventHandler; 
      c_comboBox.DropDownOpened -= eventHandler; 
      provider.Collapse(); 
     } 
    }); 
    // Anonymous delegate as event handler for ItemContainerGenerator.StatusChanged. 
    c_comboBox.ItemContainerGenerator.StatusChanged += eventHandler; 
    c_comboBox.DropDownOpened += eventHandler; 
    // Expand the c_comboBox to generate all its ComboBoxItem's. 
    provider.Expand(); 
} 

private void Window_Loaded(object sender, RoutedEventArgs e) 
{ 
    SetComboBoxWidthFromItems(); 
} 
+0

產品線,它沒有ActualWidth的財產 – 2010-10-26 15:48:55