UWP Databinding: How to set button command to parent DataContext inside DataTemplate

后端 未结 3 746
灰色年华
灰色年华 2021-01-12 09:14

Short explanation of need: I need to fire the command of a button inside a DataTemplate, using a method from the DataContext of the ViewModel.

Short explanation of p

3条回答
  •  余生分开走
    2021-01-12 10:15

    There is a few ways to do that. But i think the Command change better...

    Example, you have a (grid,list)view with some itemtemplate like that:

                        
                            
    
                                
    
                               
    
                     
    

    And do you want to make a command to for example a FlyoutMenu... But the command it's in the ViewModel and not in GridView.SelectedItem...

    What you can do is...

                            
    
                                    
                                        
    
                                            
                                                
                                            
    
                                            
                                            
    
                                        
                                    
    
    
                 
    

    And in the loaded events:

        private void mfiDeletePic_Loaded(object sender, RoutedEventArgs e)
        {
            var m = (MenuFlyoutItem)sender;
    
            if (m != null)
            {
    
                m.Command = Vm.DeleteImageCommand;
                //Vm is the ViewModel instance...
            }
        }
    

    Is not entirely beautiful... But you willnot breake mvvm pattern like this...

提交回复
热议问题