June 18, 2015 | Posted in: .Net

I needed a way to mark any control in the system so that I could check if I needed to perform some action on it. Ideally it needed to be on the base class System.Windows.Forms.Control so that this could be done on anything that inherits from it.

I used two separate extension methods to add and check for the custom attribute using the TypeDescriptor class, and then:

To add the attribute to the control with the ignoreAction value:

YourControl.IgnoreAction(True)

To check for the attribute on the control elsewhere in the system:

if (Not YourControl.IgnoreAction) or (!YourControl.IgnoreAction) if using c#

The extension methods:

Public Module Extensions
Private ReadOnly attr As New IgnoreActionAttribute(True)

<System.Runtime.CompilerServices.Extension()>
Public Sub IgnoreAction(ByVal value As System.Windows.Forms.Control, ignore As Boolean)

Try
Dim params() As Attribute = {New IgnoreActionAttribute(ignore)}

System.ComponentModel.TypeDescriptor.AddAttributes(value, params)

Catch ex As Exception
‘Handle Error
End Try

End Sub

<System.Runtime.CompilerServices.Extension()>
Public Function IgnoreAction(ByVal value As System.Windows.Forms.Control) As Boolean

Dim ignore As Boolean = False

Dim attribs As System.ComponentModel.AttributeCollection = Nothing

Try
attribs = System.ComponentModel.TypeDescriptor.GetAttributes(value)

If attribs.Contains(attr) Then
ignore = True
End If

Catch ex As Exception
‘Handle Error
End Try

Return ignore

End Function

End Module

The custom attribute:

Public Class IgnoreActionAttribute
Inherits Attribute

”’ <summary>
”’ The ignore action value.
”’ </summary>
”’ <remarks></remarks>
Private _ignoreAction As Boolean

”’ <summary>
”’ Main constructor for the ignore action attribute.
”’ </summary>
”’ <param name=”ignoreAction”></param>
”’ <remarks></remarks>
Public Sub New(ignoreAction As Boolean)
Me._ignoreAction = ignoreAction
End Sub

”’ <summary>
”’ The ignore action value.
”’ </summary>
”’ <returns>True if the action should be ignored.</returns>
”’ <remarks></remarks>
Public Property IgnoreAction() As Boolean
Get
Return Me._ignoreAction
End Get
Set(value As Boolean)
Me._ignoreAction = value
End Set
End Property

End Class

I’ve seen other implementations which are far more convoluted than this. Here you can quickly and easily add your attribute to a control, or you could extend it to add any custom attribute to any object you like and then use the TypeDescriptor to check for it.

Be the first to comment.

Leave a Reply

*


twelve − seven =


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>