Specify Command for MenuItem in a DataTemplate

后端 未结 3 467
花落未央
花落未央 2020-12-09 16:49

I have a context menu. It\'s bound to some collection and it has a defined ItemTemplate like this:



        
3条回答
  •  一向
    一向 (楼主)
    2020-12-09 17:49

    I realize I'm answering this quite a bit after the fact, but I ran into the same problem and the previous answers seemed to make binding to multiple different commands difficult. The solution I arrived is very similar to MatrixManAtYrService's and works in 3 parts:

    1) Bind the command using the ItemContainerStyle property to a command in the ViewModel -- this is the same as the previous answers. One exception is that I bind the CommandParameter to the MenuItem.

    
    

    2) Create a custom class to define the look and behavior of each MenuItem. The ItemsSource of the menu will be set to a list of these. This is the same as other answers. However, in my implementation I have given the class an Action to be executed when the MenuItemCommand is invoked. I also included a boolean that will allow the MenuItem to be disabled.

    public class MenuAction
    {
        public string Name { get => name; set => name = value; }
        public Action Action { get => action; set => action = value; }
        public bool CanExecute { get => canExecute; set => canExecute = value; }
    }
    

    3) In the command implementation route control to the delegates in MenuAction.

    public void HandleCommand(object sender)
    {
        MenuItem clickedMenuItem = sender as MenuItem;
        MenuAction menuAction = clickedMenuItem?.DataContext as MenuAction;
        if(menuAction != null)
            menuAction.Action();
    }
    
    public bool CanMenuItemExecute(object sender)
    {
        MenuItem clickedMenuItem = sender as MenuItem;
        MenuAction menuAction = clickedMenuItem?.DataContext as MenuAction;
        if (menuAction != null)
            return menuAction.CanExecute;
        else
            return false;
    }
    
    

    This should allow you to define all of the behavior of your commands in a list. While it is technically binding to a single command it is functionally similar to having multiple different commands. The same method should also work with nested MenuItems and HierarchicalDataTemplates with some tweaking.

提交回复
热议问题