WPF Databinding ContextMenu of Button inside a DataTemplate inside an ItemsControl

后端 未结 2 1365
执念已碎
执念已碎 2021-01-16 13:18

I am trying to figure out how I can bind the ContextMenu of the Button that is being added in the ItemsControl I have. Basically, I\'m wanting to be able to right click on a

2条回答
  •  青春惊慌失措
    2021-01-16 13:52

    Using WPF: Binding a ContextMenu to an MVVM Command as an introduction to what Tags can do, I figured out how to do what I was looking for by using multiple Tags to save the Context of what I was looking for.

    I first made sure to give my window a x:Name

    Next, on the Button inside my DataTemplate of my ItemsControl, I set a Tag and set it to my Window

    
        
            
                

    Next, in the ContextMenu, I seth the DataContext of the ContextMenu to the Tag I set on the Button, I also needed to create a Tag on the ContextMenu and point it back to the Content Property of the Button so that I can pass that into the CommandParameter

    
    

    At this point, I can now bind my MenuItem correctly using the Command from my ViewModel and the Content Property from the Button

    This is the final XAML for my ItemsControl:

    
        
            
                
            
        
        
            
                
            
        
    
    

    One thing to note is that I had to change the CommandParameter on my ViewModel to take an Object instead of a String. The reason I did this was because I was getting an exception on the CanExecute method in my DelegateCommand

    This is the exception I was getting:

    Unable to cast object of type 'MS.Internal.NamedObject' to type 'System.String'.
    

    I'm not sure exactly what's causing that exception to throw, but changing it to Object works ok for me.

提交回复
热议问题