ListBoxItem にコンテキスト メニューを追加するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/376910

質問

ListBox があり、リスト内の各項目にコンテキスト メニューを追加したいと考えています。右クリックで項目を選択し、空白スペースの場合はコンテキストメニューを抑制するという「解決策」を見てきましたが、この解決策は汚いように感じます。

誰かもっと良い方法を知っていますか?

役に立ちましたか?

解決

この方法では、メニューには、次の

マウスにポップアップ表示されます
private string _selectedMenuItem;
private readonly ContextMenuStrip collectionRoundMenuStrip;

public Form1()
{ 
    var toolStripMenuItem1 = new ToolStripMenuItem {Text = "Copy CR Name"};
    toolStripMenuItem1.Click += toolStripMenuItem1_Click;
    var toolStripMenuItem2 = new ToolStripMenuItem {Text = "Get information on CR"};
    toolStripMenuItem2.Click += toolStripMenuItem2_Click;
    collectionRoundMenuStrip = new ContextMenuStrip();
    collectionRoundMenuStrip.Items.AddRange(new ToolStripItem[] {toolStripMenuItem1, toolStripMenuItem2 });
    listBoxCollectionRounds.MouseDown += listBoxCollectionRounds_MouseDown;
}

private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
    var info = GetInfoByName(_selectedMenuItem);
   MessageBox.Show(info.Name + Environment.NewLine + info.Date);
}

private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
    Clipboard.SetText(_selectedMenuItem);
}

private void myListBox_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button != MouseButtons.Right) return;
    var index = myListBox.IndexFromPoint(e.Location);
    if (index != ListBox.NoMatches)
    {
        _selectedMenuItem = listBoxCollectionRounds.Items[index].ToString();
        collectionRoundMenuStrip.Show(Cursor.Position);
        collectionRoundMenuStrip.Visible = true;
    }
    else
    {
        collectionRoundMenuStrip.Visible = false;
    }
}

他のヒント

だけのFransは、リストボックスがいるContextMenuStripを所有しているにもかかわらず...言ったことに少しさらに詳しく説明するために、あなたはまだそれが開いていた時間のメニューストリップ内の項目をカスタマイズすることができます。したがって、リストボックス内のマウスの位置に基づいて、それの内容をカスタマイズする。
以下の例では、マウスの右クリックに基づいてリストボックスで項目を選択し、ユーザーが右クリックした項目に基づいて、コンテキストメニューストリップをカスタマイズします。これは単純な例ですが、あなたが軌道に乗る必要があります:フォームにリストボックスを追加し、このコードを追加します:

print("        #region Private Members
    private ContextMenuStrip listboxContextMenu;
    #endregion

    private void Form1_Load( object sender, EventArgs e )
    {
        //assign a contextmenustrip
        listboxContextMenu = new ContextMenuStrip();
        listboxContextMenu.Opening +=new CancelEventHandler(listboxContextMenu_Opening);
        listBox1.ContextMenuStrip = listboxContextMenu;

        //load a listbox
        for ( int i = 0; i < 100; i++ )
        {
            listBox1.Items.Add( "Item: " + i );
        }
    }

    private void listBox1_MouseDown( object sender, MouseEventArgs e )
    {
        if ( e.Button == MouseButtons.Right )
        {
            //select the item under the mouse pointer
            listBox1.SelectedIndex = listBox1.IndexFromPoint( e.Location );
            if ( listBox1.SelectedIndex != -1)
            {
                listboxContextMenu.Show();   
            }                
        }
    }

    private void listboxContextMenu_Opening( object sender, CancelEventArgs e )
    {
        //clear the menu and add custom items
        listboxContextMenu.Items.Clear();
        listboxContextMenu.Items.Add( string.Format( "Edit - {0}", listBox1.SelectedItem.ToString() ) );
    } ");

は、その助けを願っています。 -Mike

他に方法はありません:コンテキストメニューは、リストボックス内の項目ではなく、リストボックス自体によって所有されていません。また、代わりのTreeNodeのコンテキストメニューを所有しているツリービューコントロールに似ています。リストボックスの項目が選択されているので、いつでも、選択された項目に応じてリストボックスのコンテキストメニューを設定します。

そして、ここでは、私の解決策です。

listBox_Usernames.ContextMenuStrip = contextMenuStripRemove;
listBox_Usernames.MouseUp += new MouseEventHandler(listBox_Usernames_MouseUp);

void listBox_Usernames_MouseUp(object sender, MouseEventArgs e)
{
    int index = listBox_Usernames.IndexFromPoint(e.Location);
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        if (index != ListBox.NoMatches)
        {
            if (listBox_Usernames.SelectedIndex == index)
            {
                listBox_Usernames.ContextMenuStrip.Visible = true;
            }
            else
            {
                listBox_Usernames.ContextMenuStrip.Visible = false;
            }
        }
        else
        {
            listBox_Usernames.ContextMenuStrip.Visible = false;
        }
    }
    else
    {
        listBox_Usernames.ContextMenuStrip.Visible = false;
    }
}

は、XAMLで、それは次のように示しています:

<ListBox>
    <ListBox.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Add User..."/>
            <MenuItem Header="Edit..."/>
            <MenuItem Header="Disable"/>
        </ContextMenu>
    </ListBox.ContextMenu>
</ListBox>

コンテキストメニュー項目を有効または無効のその問題だけなら、それはコンテキストメニューが起動ではなく、毎回リストボックスの選択が変更されたときにのみ、それを行うには、より効率的かもしれません

myListBox.ContextMenu.Popup += new EventHandler(myContextPopupHandler);


private void myContextPopupHandler(Object sender, System.EventArgs e)
{
    if (SelectedItem != null)
    {
        ContextMenu.MenuItems[1].Enabled = true;
        ContextMenu.MenuItems[2].Enabled = true;
    }
    else
    {
        ContextMenu.MenuItems[1].Enabled = false;
        ContextMenu.MenuItems[2].Enabled = false;
    }
}

これが一番いいよ…

using System.Windows.Forms;

ContextMenuStrip menu;

this.menu.Items.AddRange(new ToolStripItem[] { this.menuItem });
this.listBox.MouseUp += new MouseEventHandler(this.mouse_RightClick);

private void mouse_RightClick(object sender, MouseEventArgs e)
{
    int index = this.listBox.IndexFromPoint(e.Location);
    if (index != ListBox.NoMatches)
    {
        menu.Visible = true;
    }
    else
    {
        menu.Visible = false;
    }
}

1行のコードで(複数の結合用)

var datasource = new BindingList<string>( new List<string>( new string[] { "item1" } ) );
listbox.DataSource = datasource ;
listbox.ContextMenu = new ContextMenu(
    new MenuItem[] { 
        new MenuItem("Delete", 
            new EventHandler( (s,ev) => 
            datasource.Remove(listbox.SelectedItem.ToString())
        )
    ) 
});

private void buttonAdd_Click(object sender, EventArgs e)
{
    datasource.Add( textBox.Text );
}   
//Create and Initialize the contextMenuStrip component
contextMenuStrip_ListaAulas = new ContextMenuStrip();

//Adding an Item
contextMenuStrip_ListaAulas.Items.Add("Modificar");

//Binding the contextMenuStrip with the ListBox
listBox_Aulas.ContextMenuStrip = contextMenuStrip_ListaAulas;

//The solution below 
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
    //select the item under the mouse pointer
    listBox_Aulas.SelectedIndex = listBox_Aulas.IndexFromPoint(e.Location);

    //if the selected index is an item, binding the context MenuStrip with the listBox
    if (listBox_Aulas.SelectedIndex != -1)
    {
         listBox_Aulas.ContextMenuStrip = contextMenuStrip_ListaAulas;  
    }
    //else, untie the contextMenuStrip to the listBox 
    else
    {
         listBox_Aulas.ContextMenuStrip = null;
    }
}

私はこのように行う、これは私のために素晴らしいと高速に動作します。

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
    {
        if (Listbox.SelectedItem == null)
            e.Cancel = true;
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top