2017-08-09 4 views
2

Ich schreibe eine Erweiterungsmethode die erste Steuer in Tab-Reihenfolge in einem Control wie unten zu bekommen:Wie finden Sie das erste Steuerelement in Tab-Reihenfolge in einem Steuerelement?

public static void FirstControlFocus(this Control ctl) 
{ 
    ctl.Controls.OfType<Control>().Where(c => c.TabIndex == 0).FirstOrDefault().Focus(); 
} 

Das Problem ist manchmal vielleicht gibt es keine bestehende Regelung mit TabOrder==0 (zB Entwickler löschen das! Steuerung mit Taborder==0 im Design-Modus) und dies führte zu einem Laufzeitfehler.

ich dieses Problem mit diesem Code behandeln:

public static void FirstControlFocus(this Control ctl) 
{ 
    if (ctl.Controls.OfType<Control>().Any(c => c.TabIndex == 0)) 
     ctl.Controls.OfType<Control>().Where(c => c.TabIndex == 0).FirstOrDefault().Focus(); 
    else if (ctl.Controls.OfType<Control>().Any(c => c.TabIndex == 1)) 
     ctl.Controls.OfType<Control>().Where(c => c.TabIndex == 1).FirstOrDefault().Focus(); 
    else if (ctl.Controls.OfType<Control>().Any(c => c.TabIndex == 2)) 
     ctl.Controls.OfType<Control>().Where(c => c.TabIndex == 2).FirstOrDefault().Focus(); 
    else if (ctl.Controls.OfType<Control>().Any(c => c.TabIndex == 3)) 
     ctl.Controls.OfType<Control>().Where(c => c.TabIndex == 3).FirstOrDefault().Focus(); 
} 

Aber ich denke, es ist nicht die beste Weise könnte jemand einen besseren Weg vorschlagen, um dieses Problem zu umgehen? Danke im Voraus.

Antwort

2

können Sie Min() verwenden:

public static void FirstControlFocus(this Control ctl) 
{ 
    ctl.Controls.OfType<Control>() 
     .FirstOrDefault(c => c.TabIndex == ctl.Controls.OfType<Control>().Min(t => t.TabIndex)) 
     ?.Focus(); 
} 

Es gibt keine Notwendigkeit, in Where() - Sie FirstOrDefault() nur nutzen können. Ziehen Sie auch die Verwendung von ?.Focus() für den Fall in Betracht, wenn FirstOrDefault()null zurückgibt.

+0

Was ist das '' 'nach' FirstOrDefault() '? –

+1

@combo_ci, siehe hier - https://msdn.microsoft.com/en-us/magazine/dn802602.aspx –

+0

vielen Dank Roma, ich lerne neue Dinge heute :) –

Verwandte Themen