How to implement commands to use ancestor methods in WPF?

后端 未结 5 1940
萌比男神i
萌比男神i 2020-12-20 18:11

I have this context menu resource:



        
5条回答
  •  梦毁少年i
    2020-12-20 18:49

    It is possible to create an adapter class which can be configured as a resource in XAML, can be attached to a Control in order to create CommandBindings there, and on the other end can bind to a method in the ViewModel which should be called when the command is triggered by a Button or MenuItem. The command in this case would be a RoutedCommand, and it wouldn't matter whether you choose one of the predefined WPF commands or create a custom RoutedCommand in your application.

    The trick for binding to a method is

    • Making the adapter a Freezable, so one can use the current DataContext as a binding source,
    • Giving it a DependencyProperty of type Delegate or one of its subtypes, and
    • Using a converter which accepts the method name as a ConverterParameter and inspects the binding sources type in order to create a Delegate for the method that should be invoked by the command.

    While this sounds complex, the good thing is that once you have the parts of the framework together, you can simply reuse them in XAML only, and you won't have any glue code at all in either ViewModel or code behind.

    As you can imagine, this takes some infrastructure, and the code is more than I would like to post here. However, I've just published an article in my blog on the subject, http://wpfglue.wordpress.com/2012/05/07/commanding-binding-controls-to-methods/ , and through the blog you can download complete source code for the framework and an example in VB.Net .

    Applied to your problem, the XAML would then look like this:

    In the definition of the ContextMenu:

    
    
        
        
            
                
            
        
    
    
    

    And in the definition of the DataGrid

    
        
            
            
    
    

提交回复
热议问题