listbox-contextmenu
文件大小: unknow
源码售价: 5 个金币 积分规则     积分充值
资源说明:How to bind a ContextMenu to a ListBox in WPF. Pure MVVM solution without any code-behind.
My goal was to bind a WPF ContextMenu located in a ListBox to a command the MVVM way without any code-behind. I thought this should be a trivial thing. I was totally wrong. After spending several hours googling for a solution and failing to apply every single of them, I decided to ask guidance to my friend Mathieu who is a WPF genius. He found a cool solution which I publish here for the benefit of community.

### My message to Mathieu: 

> I'm going crazy with a problem of ContextMenu in a ListBox. I am not able to bind a command to a context menu. I did a small project to reproduce my problem. I have a listbox bound on a view model. In this model I have a command that displays a message with the items selected from the list. I bound this command to three elements: a menu item in a menu bar, a button in a tool bar and finally a menu item the listbox context menu. The binding of the context menu does not work but it works for two other elements. I'm really desperate. It seems to be a known problem because the context menu is not in the visual tree. I am looking for a solution without code-behind and the ones I found on the web does not work for me (or I do not understand how they work). Therefore I ask your help when you have the time. 

> Thank you.

> Manuel

### His reply with the solution:

> This was not an easy one. I had to Google and try a lot. But I found a solution that works perfectly and reasonably concise. I "pushed" the solution in your Git repo. Below is the new XAML with the changes.

> In short, as the ContextMenu is not part of the visual tree, it is very difficult to bind the ListBox from it. So I inverted a few conventions and I passed the ListBox in the DataContext of the ContextMenu. Then I am able find the command in the view model by accessing the DataContext of the ListBox. The clue I found on Google is to use the ContextMenu property PlacementTarget to access the ListBox. This is slightly twisted, but once you think about it, it's not that complicated. 

> Happy coding!

> Mathieu

    
      
        
          
            
          
          
            
              

本源码包内暂不包含可直接显示的源代码文件,请下载源码包。