通过绑定创建其他上下文菜单项

时间:2021-05-30 20:21:01

I need a context menu that has additional items based on a list.
Currently I'm doing this by looping through the list and adding the items like this:

我需要一个上下文菜单,其中包含基于列表的其他项目。目前我通过循环遍历列表并添加如下项目来执行此操作:

var MyItemsList = new List<string>{
 "item1"
 "item2"
};
myContextMenu.Items.Clear();
foreach (var item in MyItemsList)
{
    var menuItem = new MenuItem();
    menuItem.Header = item;
    menuItem.Click += (sender, args) => HandleItem(item);
    myContextMenu.Items.Add(menuItem);
}
myContextMenu.Add(new MenuItem {Header = "Static item"}); //etc, etc

How can I do this in XAML using bindings?

如何使用绑定在XAML中执行此操作?

1 个解决方案

#1


0  

You have to put everything in a Collection, and set that Collection as the ItemsSource of your ContextMenu. You cannot set ItemsSource for only half of the MenuItems. Though you can use nested MenuItems for which you can set ItemsSource.

您必须将所有内容放在Collection中,并将该Collection设置为ContextMenu的ItemsSource。您不能仅为MenuItem的一半设置ItemsSource。虽然您可以使用嵌套的MenuItems,您可以为其设置ItemsSource。

For example you can have :

例如,您可以:

  • MenuItem1
  • MenuItem1
  • MenuItem2
  • MenuItem2
  • MenuItem3
    • SubMenu1
    • SubMenu1
    • SubMenu2
    • SubMenu2
  • MenuItem3 SubMenu1 SubMenu2

MenuItem3 is having its ItemsSource set.

MenuItem3设置了ItemsSource。

#1


0  

You have to put everything in a Collection, and set that Collection as the ItemsSource of your ContextMenu. You cannot set ItemsSource for only half of the MenuItems. Though you can use nested MenuItems for which you can set ItemsSource.

您必须将所有内容放在Collection中,并将该Collection设置为ContextMenu的ItemsSource。您不能仅为MenuItem的一半设置ItemsSource。虽然您可以使用嵌套的MenuItems,您可以为其设置ItemsSource。

For example you can have :

例如,您可以:

  • MenuItem1
  • MenuItem1
  • MenuItem2
  • MenuItem2
  • MenuItem3
    • SubMenu1
    • SubMenu1
    • SubMenu2
    • SubMenu2
  • MenuItem3 SubMenu1 SubMenu2

MenuItem3 is having its ItemsSource set.

MenuItem3设置了ItemsSource。

相关文章