2

我有以下代码(简化):

private ContextMenuStrip createContextMenuStrip(Card card)
{
    ContextMenuStrip cms = new ContextMenuStrip();
    cms.Items.Add("Send to the top of the deck", null, sendToDeck);
    return cms;
}

public void sendToDeck(object sender, EventArgs e)
{
    // **
}

该类Card有一个类型的成员PictureBox。在此PictureBoxContextMenu将创建。到目前为止,这非常有效,但是:

在这里,我想访问包含单击的 PictureBox 的相应 Card 类的实例ContextMenu

我有什么可能实现这一目标?

4

2 回答 2

4

您可以使用可以引用您的变量的lambda 表达式card(请参阅“Lambda 表达式中的变量范围”)并将其传递给您的方法:

private ContextMenuStrip createContextMenuStrip(Card card)
{
    ContextMenuStrip cms = new ContextMenuStrip();
    cms.Items.Add("Send to the top of the deck", 
                  null, 
                  (sender, e) => sendToDeck(sender, e, card));
    return cms;
}

public void sendToDeck(object sender, EventArgs e, Card card)
{
    // **
}

但是,假设您不关心输入object senderEventArgs e输入,它就会变成:

private ContextMenuStrip createContextMenuStrip(Card card)
{
    ContextMenuStrip cms = new ContextMenuStrip();
    cms.Items.Add("Send to the top of the deck", 
                  null, 
                  (sender, e) => sendToDeck(card));
    return cms;
}

public void sendToDeck(Card card)
{
    // **
}
于 2013-09-10T15:37:02.953 回答
2

Control具有Tag类型的属性object,您可以在其中存储链接到控件的数据。在您的情况下,您可以存储卡:

private ContextMenuStrip createContextMenuStrip(Card card)
{
    ContextMenuStrip cms = new ContextMenuStrip();
    var item = cms.Items.Add("Send to the top of the deck", null, sendToDeck);
    item.Tag = card; // so you have the card in your contextmenu
    return cms;
}

然后你可以在事件中恢复

public void sendToDeck(object sender, EventArgs e)
{
    var card = (Card)((Control)sender).Tag;
}
于 2013-09-10T15:48:30.117 回答