禁用按钮的上下文菜单

3

我想创建一个上下文菜单,当用户在控件(按钮)上进行“右键单击”时显示。不幸的是,有些按钮被禁用了。有人可以帮助我吗?告诉我如何也为它们添加上下文菜单?

我的(无效的)尝试:

        private void ShowRightClickMenu(object sender, MouseEventArgs e)
    {
        ContextMenu Temp = new ContextMenu();
        if (e.Button == MouseButtons.Right && secondTagObj[Convert.ToInt32(((Button)sender).Tag)].typ != string.Empty)
        {
            this.ContextMenu = Temp;        // works
            Temp.MenuItems.Add("Create.."); //works
            Temp.MenuItems.Add("Delete");   // works
        }
        if (raster[Convert.ToInt32(((Button)sender).Tag)].Enabled == false && e.Button == MouseButtons.Right)
        {
            this.ContextMenu = Temp;        // works not
            Temp.MenuItems.Add("New...");   // works not
        }
        else
        {
            this.ContextMenu = Temp;        // works, but only if button is visible
            Temp.MenuItems.Add("New...");   // works, but only if button is visible
        }
    }

非常感谢您提前的帮助。

2个回答

2

(假设这个问题是关于WPF的,因为在@medasocles答案的评论中有所指示...)

要在WPF中使用ContextMenuService,您需要执行以下操作:

<Button Content="Blah" Command="{Binding MyCommand}" ContextMenuService.ShowOnDisabled="True">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Context Item" Command="{Binding MyContextCommand}" />
        </ContextMenu>
    </Button.ContextMenu>
</Button>

我不认为这个方法能够解决你的问题。我认为更简单的做法是将你的按钮放在一个框架中,就像边框一样,并将上下文菜单添加到边框中。然后,当按钮被禁用时,我会为按钮添加一个触发器,将IsHitTestVisible设置为False,从而允许交互通过到背后的边框,并使你的菜单按预期工作。


这完美地解决了我的问题 :) - Jon Barker

1
在WPF中,您可以使用ContextMenuService为禁用的控件启用上下文菜单。
private void ShowRightClickMenu(object sender, MouseEventArgs e)
{
    ContextMenu Temp = new ContextMenu();
    ContextMenuService.SetShowOnDisabled((Button)sender, true);
...

[为了更好的可读性更新] 对于WinForms,请查看微软论坛上的这篇文章 希望这可以帮到你。

很遗憾,这是一个普通的表单而不是Wpf,所以我不能使用System.Windows.Controls。但还是谢谢 :) - BudBrot
这太糟糕了,但你可以看看这个链接,也许能帮到你:链接 - medasocles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接