2010-02-05 4 views

Antwort

40

Ich verwende eine Erweiterungsmethode, um Steuerhierarchie abzuflachen und dann Filter anzuwenden, so dass eine eigene rekursive Methode verwendet wird.

Das Verfahren sieht wie folgt aus

public static IEnumerable<Control> FlattenChildren(this Control control) 
{ 
    var children = control.Controls.Cast<Control>(); 
    return children.SelectMany(c => FlattenChildren(c)).Concat(children); 
} 
+1

Könnten Sie bitte ein Beispiel für Code angeben? – abatishchev

+1

sicher, fügte den Code –

+1

Wirklich schönes Stück Code, vielen Dank für die Freigabe! –

1

oben Antwort zu verbessern, wäre es sinnvoll, um den Rückgabetyp zu wechseln

//Returns all controls of a certain type in all levels: 
public static IEnumerable<TheControlType> AllControls<TheControlType>(this Control theStartControl) where TheControlType : Control 
{ 
    var controlsInThisLevel = theStartControl.Controls.Cast<Control>(); 
    return controlsInThisLevel.SelectMany(AllControls<TheControlType>).Concat(controlsInThisLevel.OfType<TheControlType>()); 
} 

//(Another way) Returns all controls of a certain type in all levels, integrity derivation: 
public static IEnumerable<TheControlType> AllControlsOfType<TheControlType>(this Control theStartControl) where TheControlType : Control 
{ 
    return theStartControl.AllControls().OfType<TheControlType>(); 
} 
1

Ich benutze diese allgemeine rekursive Methode:

Die Annahme, dieser Methode ist, dass, wenn das Steuerelement T ist als die Methode nicht in seinen Kindern suchen. Wenn Sie auch auf seine Kinder schauen müssen, können Sie es leicht entsprechend ändern.

Verwandte Themen