为多个对象使用事件处理程序 [英] Using Event Handlers for Multiple Objects

查看:21
本文介绍了为多个对象使用事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 List 中有 20 个项目.每个都有一个与它相关联的 UserControl 实例.每个对象都可以通过 MenuStrip 访问,当单击适当的项目时,它需要显示 UserControl.目前,我为它们中的每一个都有一个事件处理程序,它可以工作,但我想知道是否存在一种方法来简化它并对所有项目使用单个事件处理程序.

I have 20 items in a List<myObject>. Each has an instance of a UserControl associated with it. Each object is accessible via a MenuStrip that needs to display the UserControl when the appropriate item is clicked. Currently I have an event handler for each of them, which works, but I was wondering if a way exists to simplify this and use a single event handler for all of the items.

这可能吗?如果是这样,最好的方法是什么.

Is this possible? If so what is the best way to go about doing so.

其他人可以就这个问题提供任何意见吗?我对Mailo的回答有问题.基本上我需要做的就是创建一个事件处理程序,当单击正确的 MenuStrip 项时,该事件处理程序可以将存储在 List 中的相应 UserControl 作为属性显示出来.有没有更直接的方法来做到这一点?理想情况下,我想让 foreach 循环可以遍历列表并设置处理程序.

Can anybody else provide any input on this issue? I'm having trouble with Mailo's answer. Essentially all I need to do is make an event handler that can display the appropriate UserControl stored in a List<myObject> as a property when the correct MenuStrip item is clicked. Is there a more straightforward way to do this? Ideally I'd like to make it so that a foreach loop can go through the list and set up the handlers.

没有人可以帮我解决这个问题吗?

Is there nobody who can help me with this?

推荐答案

这并不难.首先,您需要某种方式将菜单项与列表中的控件相关联.

It's not very difficult. First is you need some way to associate a menu item with a control in the list.

1) 由于您有一个列表,因此索引是最简单的方法(您可以使用 Dictionary<> 来简化这种关联).因此,假设当您单击第一个菜单项时,您希望 myObjecList[0] 出现.当您单击第二个 MenuItem 时,会出现 myObjectList[1],依此类推.为此,请转到每个菜单项,然后在属性"中为 Tag 属性分配一个值.对于第一个菜单项,将 Tag 分配给 0,对于第二个菜单项,将 Tag 分配给 1 - 以此类推.

1) Since you have a list, index is simplest way ( you could use Dictionary<> to simplify this association). So, lets say when you click the first menu item, you want myObjecList[0] to appear. When you click second MenuItem, myObjectList[1] would appear and so on. For this go to each menu item, and in the Properties, assign a value to Tag property. For first menu item, assign Tag to 0, for second item, assign Tag to 1 - and so on.

2) 创建一个事件处理程序并将相同的处理程序分配给所有菜单项.事件处理程序可能如下所示:

2) Create one event handler and assign the same handler to all menu items. The event handler could look something like this:

private void myToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // source menu item which was clicked
            ToolStripMenuItem item = sender as ToolStripMenuItem;

            if(item != null) 
            {
                int index = int.Parse(item.Tag.ToString()); // get the index from Tag
                myObject control = myObjectList[index];

                // do your stuff with your control

            }
        } 

这篇关于为多个对象使用事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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