1

我正在尝试获取生成上下文菜单的控件,因为将有多个列表视图使用相同的上下文菜单。

我以前做过,但现在我在上下文菜单中使用嵌入式组合框似乎变得复杂了 1000 倍:

在此处输入图像描述

当我在组合框中选择一个项目时,我需要确定哪个列表视图产生了菜单:

private void tsCboAddCharList_SelectedIndexChanged(object sender, EventArgs e) {
    if (tsCboAddCharList.SelectedItem == null) return;

    ContextMenuStrip theTSOwner;

    if (sender.GetType().Name.Contains("ToolStripComboBox")) {

        ToolStripComboBox theControl = sender as ToolStripComboBox;
        ToolStripDropDownMenu theMenu = theControl.Owner as ToolStripDropDownMenu;
        ContextMenuStrip theTlStrip = theMenu.OwnerItem.Owner as ContextMenuStrip;

        ContextMenuStrip theCtxStrip = theTlStrip as ContextMenuStrip;

        theTSOwner = theCtxStrip;
    } else {
        theTSOwner = (ContextMenuStrip)((ToolStripItem)sender).Owner;
    }

    ListView callingListV = (ListView)theTSOwner.SourceControl; //always null

我究竟做错了什么?

4

1 回答 1

2

试试这个代码:

private void tsCboAddCharList_SelectedIndexChanged(object sender, EventArgs e)
{
    // Cast the sender to the ToolStripComboBox type:
    ToolStripComboBox cmbAddCharList = sender as ToolStripComboBox;

    // Return if failed:
    if (cmbAddCharList == null)
        return;

    if (cmbAddCharList.SelectedItem == null)
        return;

    // Cast its OwnerItem.Owner to the ContextMenuStrip type:
    ContextMenuStrip contextMenuStrip = cmbAddCharList.OwnerItem.Owner as ContextMenuStrip;

    // Return if failed:
    if (contextMenuStrip == null)
        return;

    // Cast its SourceControl to the ListView type:
    ListView callingListV = contextMenuStrip.SourceControl as ListView;
    // Note: it could be null if the SourceControl cannot be casted the type ListView.
}

如果您完全确定只能为此特定菜单项调用此事件处理程序,则可以省略检查(但我不建议这样做):

private void tsCboAddCharList_SelectedIndexChanged(object sender, EventArgs e)
{
    if (tsCboAddCharList.SelectedItem == null)
        return;

    // Cast the OwnerItem.Owner to the ContextMenuStrip type:
    ContextMenuStrip contextMenuStrip = (ContextMenuStrip)tsCboAddCharList.OwnerItem.Owner;

    // Cast its SourceControl to the ListView type:
    ListView callingListV = (ListView)contextMenuStrip.SourceControl;
}
于 2014-11-04T18:51:45.653 回答