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 に答える