自定义事件取消 [英] Custom Event with Cancel

查看:92
本文介绍了自定义事件取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在自定义控件中创建一个能够被窗体事件处理程序取消的事件。如果事件在外部事件发生之前就会看到这样做?

解决方案

您可以复制KeyPress事件。



从代码触发时,KeyPress事件传递KeyEventArgs对象。这个对象有一个名为Handled的属性。



因此,创建自己的EventArgs类并添加一个名为Handled的属性,它是一个布尔值。初始化自定义类时,将Handled设置为false。然后,用户可以选择将handle设置为true,并在引发事件后检查该值。



如果Handled等于true,则不执行任何操作进一步。如果没有,则按正常方式处理。


带取消属性的​​自定义事件参数

 Public Class MyEventArgs 
Inherits EventArgs
Private CancelValue As Boolean = False
Sub New()
MyBase.New()
End Sub
Public Property Cancel As Boolean
Get
返回CancelValue
结束获取
设置(值为布尔值)
CancelValue = value
结束集
结束物业
结束等级





当你在引发事件的类中使用事件时,你可以引发事件并在执行代码之前等待。例如:



 Public Class MyObject 
Public Event MyEvent(e As MyEventArgs)

Public Sub MySub ()
Dim MyEvent1 As New MyEventArgs()

RaiseEvent MyEvent(MyEvent1)

如果MyEvent.Cancel = False那么
'Do thing
否则
'不做该事
结束如果
结束次级
结束等级





当对象引发事件时,只需设置e.cancel = True,如下所示:



 Private Sub MyObject1_MyEvent (e As MyEventArgs)处理MyObject1.MyEvent 

如果SomethingHappens然后
e.cancel = True
结束如果

结束Sub


I need to make an event in a custom control that has the ability to be canceled by the forms event handler. How does one do this seeing as the event fires internally before externally?

解决方案

You can copy the KeyPress event.

The KeyPress event when fired from code passes a KeyEventArgs object. This object has a property called Handled.

So, create your own EventArgs class and add a property called Handled that is a boolean value. When you initialize your custom class, you set Handled to false. Then, the user has the option to set handled to true and you check that value after you raise the event.

If Handled equals true, you don't do anything further. If not, you process it as normal.


The custom event arguments with a cancel property

Public Class MyEventArgs
    Inherits EventArgs
    Private CancelValue As Boolean = False
    Sub New()
        MyBase.New()
    End Sub
    Public Property Cancel As Boolean
        Get
            Return CancelValue
        End Get
        Set(value As Boolean)
            CancelValue = value
        End Set
    End Property
End Class



When you use the event in the class that raises the event you can raise the event and wait before you execute code. example:

Public Class MyObject
    Public Event MyEvent(e As MyEventArgs)

    Public Sub MySub()
        Dim MyEvent1 As New MyEventArgs()

        RaiseEvent MyEvent(MyEvent1)

        If MyEvent.Cancel = False Then
            'Do the thing
        Else
            'Don't do the thing
        End If
    End Sub
End Class



When the event gets raised by the object simply set e.cancel = True like the following:

Private Sub MyObject1_MyEvent(e As MyEventArgs) Handles MyObject1.MyEvent

    If SomethingHappens Then
        e.cancel = True
    End If

End Sub


这篇关于自定义事件取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆