有没有办法做到以下几点?
For each ctrl as Control in Me.Controls.Where(function(x) x.Enabled = False)
ctrl.Enabled = True
Next
我尝试的每一种方式都得到'Where' is not a member of 'System.Web.UI.ControlCollection'
大概是因为ControlCollection
不可枚举?
答案 0 :(得分:5)
大多数LINQ扩展方法扩展了类型安全IEnumerable(Of T)
。
ControlCollection
早于泛型,只实现IEnumerable
,因此扩展方法不起作用。
您需要致电.Cast(Of Control)()
以返回IEnumerable(Of Control)
,这将接受扩展程序。
答案 1 :(得分:2)
因为ControlCollection不可枚举
不,因为它没有实现IEnumerable(Of T)
(历史原因)。
如您所知,集合中只有Control
个实例可以转换:
Me.Controls.OfType(Of Control)().Where(…
OfType(Of T)
是一种扩展IEnumerable
以返回IEnumerable(Of T)
的方法。
答案 2 :(得分:0)
该类仅实现IList, ICollection, IEnumerable, ICloneable
但不实现所需的IEnumerable(Of T)
,因此除非您先Where
,否则无法使用Cast(Of T)
。
请记住Imports System.Linq
然后您可以执行以下操作:
For each ctrl as Control in Me.Controls.Cast(Of Control).Where(function(x) x.Enabled = False)
ctrl.Enabled = True
Next
注意:并非所有控件都具有Enabled
属性,因此您不必使用Cast(Of Control)
使用OfType()
来过滤您之后的特定控件,然后设置enabled属性。< / p>
答案 3 :(得分:0)
你必须在整个ControlCollection上的每个Control上强加 .Where(function ...),不是。并且你只能在System.Windows.Forms.ControlCollection上执行此操作,而不是System.Web.UI ..因为System.Web.Ui.Control没有启用属性。
试试这个:
For each ctrl as Control in Me.Controls.Cast(Of Control)
If (Not crtl.Enabled) Then
ctrl.Enabled = True
End If
Next
答案 4 :(得分:0)
As System.Web.UI.Control
doesn't have an Enabled
property, you need to find a class (or classes) that inherits from Control
and that your controls all inherit from and that has an Enabled
property. Most of the simple controls inherit from System.Web.UI.WebControls.WebControl
which has an Enabled
property. You can process all the controls of type WebControl
like this.
For Each wCtrl As WebControls.WebControl In Me.Controls.OfType(Of WebControls.WebControl)
wCtrl.Enabled = True
Next
答案 5 :(得分:0)
System.Web.UI.Control not all have the Enabled property. You must verify their existence. For Framework 3.5
Private Function ExistPropertyEnabled(ByVal p As Reflection.PropertyInfo) As Boolean
Return (p.Name = "Enabled")
End Function
Private Sub EnabledControls()
Dim evalEnabled As Predicate(Of Reflection.PropertyInfo) = AddressOf ExistPropertyEnabled
For Each ctrl As Control In Me.Controls.Cast(Of Control)()
Dim ExistProperty As Boolean = Array.Exists(Of Reflection.PropertyInfo)(ctrl.GetType().GetProperties(), evalEnabled)
If (ExistProperty AndAlso Not ctrl.Enabled) Then
ctrl.Enabled = True
End If
Next
End Sub