我正在使用自定义控件开发自定义库。当用户在自定义属性中插入无效值时,我需要Visual Studio在设计模式下显示消息,就像Visual Studio在Button中尝试使用Color.Transparent for BorderColor时那样。
一段代码:
Public Class ButtonWithBrigthness 'It inherits from Button in .Designer.vb
Private _brigthness As Integer
Public Property Brightness() As Integer
Get
Return _brigthness
End Get
Set (value as Integer)
If (value >= 0 And value <= 10) Then
_brigthness = value
Else
'Throw Exception for an invalid value....
End If
End Set
End Property
End Class
答案 0 :(得分:1)
要知道您是否处于设计模式,可以使用DesignMode Property。
接下来,您需要知道,如果您在设计模式中从属性设置器中引发异常,属性网格将捕获它并显示一个消息框,说明&#34;无效的属性值&#34;,用户可以单击on&#34;详情&#34;查看您输入的自定义消息。 如果你想做得更好,你会显示一个消息框,说明它无法正常工作的原因。
无论如何,如果你想提出例外:
Public Property Brightness() As Integer
Get
Return _brigthness
End Get
Set (value as Integer)
'I rewrote the condition, but you don't have to, just put the exception in the else...
If value < 0 Or value > 10 Then
'Here we throw the Exception only in design mode
'So at runtime just nothing will happen...
If Me.DesignMode Then
Throw New ArgumentOutOfRangeException("Brightness must be between 0 and 10")
End If
Else
_brigthness = value
End If
End Set
End Property
如果你想展示一个漂亮的消息框......
Public Property Brightness() As Integer
Get
Return _brigthness
End Get
Set (value as Integer)
If value < 0 Or value > 10 Then
'Here we show the MessageBox only in design mode
'So at runtime just nothing will happen...
If Me.DesignMode Then
MessageBox.Show("Brightness must be between 0 and 10", "Invalid Brightness Value")
End If
Else
_brigthness = value
End If
End Set
End Property