如何在运行时将ContextMenu添加到按钮

时间:2014-01-27 08:54:56

标签: c# wpf browser

我在运行时向我的按钮添加ContextMenu时遇到问题。 我知道这是通过XAML将它添加到现有按钮的方法:

<Button.ContextMenu>
    <ContextMenu>
        <MenuItem Header="Delete"/>
    </ContextMenu>
</Button.ContextMenu>

但是应该可以将它添加到不存在的按钮,对吗?我正在根据文件中的数据添加我的按钮:

for (int a = 0; a < File.ReadAllLines(@"bookmarks.txt").Count(); a++) //add already existing bookmarks
{
    index = Array.FindIndex(bookmarks, i => i == null || i.Length == 0); //find closest empty spot in array
    bookmarks[index] = getbook[a];
    book[index] = new Button();
    book[index].Height = 31;
    book[index].Content = bookmarks[index];
    book[index].Click += Button_Click;
    Bookbar.Items.Add(book[index]);

}

我正在寻找一个处理程序,但我似乎无法找到它。那么,如何以编程方式向按钮添加右键菜单?

1 个答案:

答案 0 :(得分:2)

如果您使用Wpf就是这样做的方式:

private void InitializeItems()
        {
            for (int a = 0; a < File.ReadAllLines(@"bookmarks.txt").Count(); a++) //add already existing bookmarks
            {
                index = Array.FindIndex(bookmarks, i => i == null || i.Length == 0); //find closest empty spot in array
                bookmarks[index] = getbook[a];
                Button button = new Button();
                book[index] = button;
                book[index].Height = 31;
                book[index].Content = bookmarks[index];
                book[index].Click += Button_Click;
                Bookbar.Items.Add(book[index]);

                button.MouseRightButtonDown += button_MouseRightButtonDown;

            }

        }

        void button_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            Button button = sender as Button;
            ContextMenu menu = new ContextMenu();
            menu.Items.Add(new MenuItem() { Header = "Delete" });

            button.ContextMenu = menu;

        }

希望这有帮助