我正在尝试抓取生成上下文菜单的控件,因为会有几个listview使用相同的上下文菜单。
之前我已经这样做了,但是现在我在上下文菜单中使用嵌入式组合框似乎已经变得复杂了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
我做错了什么?
答案 0 :(得分:1)
试试这段代码:
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;
}