动态按钮上的AddHandler事件,VB.NET中的实例属性不正确 [英] AddHandler event on dynamic button, incorrect instance properties in VB.NET

查看:227
本文介绍了动态按钮上的AddHandler事件,VB.NET中的实例属性不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是自定义类的新手。我有一堂课叫做游戏。在课堂上,我有一个名为 addGame()的方法,该方法创建了一个名为 pBox的动态图片框。创建控件后,我将执行以下操作来注册click事件:

I'm new to custom classes. I have a class called 'game'. In the class, I have a method called 'addGame()' that creates a dynamic picture box called 'pBox'. After creating the control, I'm doing the following to register a click event:

AddHandler pBox.Click, AddressOf Me.launchGame

这是launchGame:

And here is launchGame:

Public Sub launchGame()
    MsgBox(Me.name)
End Sub

问题是, Me.name始终是最近添加的实例名称,而不是我单击的实例名称。

The problem is, "Me.name" is always the most recently added instances name, not the one I clicked on.

根据一个建议,我也尝试了以下方法:

Based on a suggestion, I also tried this:

Public Sub launchGame(ByVal sender As Object)
    MsgBox(sender.name)
End Sub

但是现在 AddHandler pBox.Click,AddressOf Me.launchGame


方法'Public Sub launchGame(sender As Object) '没有与委托'Delegate Sub EventHandler(sender as Object,e As System.EventArgs)'兼容的签名。

Method 'Public Sub launchGame(sender As Object)' does not have a signature compatible with delegate 'Delegate Sub EventHandler(sender As Object, e As System.EventArgs)'

添加处理程序pBox.Click,AddressOf Me.launchGame(Me)


AddressOf操作数必须是不带方法的名称括号

AddressOf operand must be the name of a method without parentheses







Public Sub launchGame(ByVal sender As Object, ByVal sender as EventArgs)
    MsgBox(sender.name)
End Sub

现在没有错误,但是msgBox为空。

Now no errors, but the msgBox is blank.

推荐答案

我认为问题在于pBox始终是最新的pictureBox控件。我基于 创建了一个控件数组Visual Basic .NET和Visual C#.NET (MSDN)中的控件数组。

I think the problem was that pBox was always the most recent pictureBox control. I created a control Array based on Creating Control Arrays in Visual Basic .NET and Visual C# .NET (MSDN).

现在,我在pBoxArray类的AddNewpBox()方法中执行AddHandler。
正如David Brunow所建议的,我还创建了一个列表来处理游戏类。然后,将pictureBox的 Tag属性设置为游戏数组中游戏的索引。

Now I do the AddHandler in the AddNewpBox() method of my pBoxArray class. I also created a list to handle the "game" class, as suggested by David Brunow. Then I'm setting the pictureBox "Tag" property to the index of the game in the "games" array.

现在,我的点击处理程序如下所示,并且

So now my click handler looks like the following, and it seems to work great.

Public Sub pBoxClick(ByVal sender As Object, e As EventArgs)
    MsgBox(games(sender.tag).name)
End Sub

这篇关于动态按钮上的AddHandler事件,VB.NET中的实例属性不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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