Command Binding in hierarchical datatemplate

前端 未结 3 541
遇见更好的自我
遇见更好的自我 2021-02-06 09:45

I have Menu in my app. I\'m visualizing it using hierarchical data template:

             


        
3条回答
  •  不要未来只要你来
    2021-02-06 10:20

    The difference between the first and the second example in your question is that in the second code snippet you are binding MenuItem.Command to the parent's data context, which has the RunOperationCommand defined. Whereas in the first example with the HierarchicalDataTemplate you are binding to the "local" DataContext, which is a menu item. It doesn't have the appropriate property, so the binding fails.

    You have several options:

    • one is to extend your menu items with the command property, like you did in your answer already;
    • bind to the relative source up in the visual tree, which has the data context with the command, e.g. assuming that the command is in your window's DataContext:

        
                                
                                        
                    
                
            
        
    

    • Make a StaticResource from your command, similar to this blog post approach

    
         
    
    
        
                                
                                        
                    
                
            
        
    

提交回复
热议问题