2011-05-31 39 views

回答

2

您可以遍歷所有控件。例如:

foreach (var ctrl in LayoutRoot.Children) 
{ 
     if (ctrl is Button) 
     ((Button)ctrl).IsEnabled = false; 
} 

當然,LayoutRoot是默認的名稱。如果需要,您可以將其更改爲另一個容器。

編輯爲允許遞歸嵌套面板(在評論中提到)。

private void DisableAllButtons(Panel parent) 
{ 

    foreach (var ctrl in parent.Children) 
    { 

     if (ctrl is Button) 
     { 

      ((Button)(ctrl)).IsEnabled = false; 

     } 
     else 
     { 
      if (ctrl is Panel) 
      { 
        if (((Panel)ctrl).Children.Count > 0) 
        { 

         DisableAllButtons((Panel)ctrl); 

        } 
       } 

     } 

    } 

    } 
+0

這不需要遞歸地完成?例如,如果'LayoutRoot'包含另一個包含'Button'的Panel。 – Praetorian 2011-05-31 23:12:05

+0

@Praetorian:我假定用戶只是指一個容器,但是你是對的,如果該容器包含另一個容器,那麼它將需要遞歸地完成。 @Tony - 你有嵌套的容器嗎? – keyboardP 2011-05-31 23:15:46

+0

編輯答案只是有嵌套面板。 – keyboardP 2011-05-31 23:23:22

1

那麼,DisableAllButtons()有時可能會工作,但通常是不夠的。這是一個真實世界的例子。 (經過一些簡化。)

 
ListBox 
    ScrollViewer 
    Border 
     Grid 
     ScrollContentPresenter 
      ItemsPresenter 
      VirtualizingStackPanel 
       ListBoxItem 
       ContentPresenter 
        Grid 
        TextBlock 
        TextBlock 
        Button 
       ListBoxItem 
       ContentPresenter 
        Grid 
        TextBlock 
        TextBlock 
        TextBlock 
     ScrollBar 
      Grid 
      Grid 
       RepeatButton 
       Thumb 
       Rectangle 
       RepeatButton 

如果你想要一個可靠的解決方案,然後代替枚舉面板小孩使用 VisualTreeHelper類及其方法GetCildrenCount()和GetChild()。這是代碼:

void DisableAllButtons(FrameworkElement fe) 
{ 
    if (fe is Button) 
     ((Button)(fe)).IsEnabled = false; 

    int count = VisualTreeHelper.GetChildrenCount(fe); 
    for (int index = 0; index < count; ++index) 
    { 
     DisableAllButtons((FrameworkElement)VisualTreeHelper.GetChild(fe, index)); 
    } 
}