2017-08-09 71 views
2

我写一个扩展方法来获取选项卡中的第一控制为了在Control如下:如何在控件的Tab键顺序中找到第一个控件?

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

的问题是有时候可能没有与TabOrder==0没有现有的控制(例如开发人员删除!在设计模式下使用Taborder==0进行控制),这会导致运行时出错。

我这段代码解决这个问题:

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

但我认为这不是最好的方式,任何人都可以提出一个更好的方式来处理这个问题?提前致谢。

回答

2

您可以使用Min()

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

有一个在Where()没有必要 - 你只能使用FirstOrDefault()。另外,如果FirstOrDefault()返回null,则考虑使用?.Focus()

+0

'FirstOrDefault()'后面的'?'是什么? –

+1

@combo_ci,看到这里 - https://msdn.microsoft.com/en-us/magazine/dn802602.aspx –

+0

非常感谢罗姆人,我今天学到了新东西:) –

相关问题