简体   繁体   English

如果未选择任何内容,请勿显示上下文菜单

[英]Don't show context menu if nothing is selected

I like to have a context menu only show up if an item is actually selected in a listbox in a winforms c# application. 我想只显示一个上下文菜单,如果在winforms c#应用程序的列表框中实际选择了一个项目。

Currently, I am able to select an item if it is right clicked properly, and I can disable the right click menu if nothing is selected, however, I don't want the menu to even show up. 目前,我可以选择一个项目,如果它被正确点击,如果没有选择任何内容我可以禁用右键菜单,但是,我不希望菜单显示。

how can this be accomplished? 怎么能实现呢?

private void genPassMenu_Opening(object sender, CancelEventArgs e)
    {
        genPassMenu.Enabled = lstPasswords.SelectedIndex > 0;
        genPassMenu.Visible = lstPasswords.SelectedIndex > 0;

    }

I tried both of those situations on their own, and it only works for enabled. 我自己尝试了这两种情况,它只适用于启用。
Perhaps Opening isn't the correct event to choose? 也许Opening不是正确的选择事件?
Tx TX

Try this: 尝试这个:

private void genPassMenu_Opening(object sender, CancelEventArgs e)
{
    //if (lstPasswords.SelectedIndex == -1) e.Cancel = true;
    e.Cancel = (lstPasswords.SelectedIndex == -1);
}

Easy, 简单,

    private void genPassMenu_Opening(object sender, CancelEventArgs e) 
    { 
        e.Cancel = (lstPasswords.SelectedIndex == 0); 

    } 

I typically set the properties of each context menu item according to its appropriateness for the particular GUI element that is selected. 我通常根据每个上下文菜单项对所选特定GUI元素的适当性来设置它们的属性。 Perhaps by setting the visible attribute on each menu item, rather than the whole menu, you can get the results that you want. 也许通过在每个菜单项而不是整个菜单上设置visible属性,您可以获得所需的结果。

private void genPassMenu_Opening(object sender, CancelEventArgs e)
    {
        //genPassMenu.Enabled = lstPasswords.SelectedIndex > 0;
        //genPassMenu.Visible = lstPasswords.SelectedIndex > 0;
        e.Cancel = (lstPasswords.SelectedIndex <= 0);


    }

I saw when the above did hte opposite I reversed the code slightly. 我看到上面的内容确实相反,我稍稍颠倒了代码。 For some reason having the equality also didn't work. 出于某种原因,平等也没有奏效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM