binding a command inside a listbox item to a property on the viewmodel parent

后端 未结 7 2104
北海茫月
北海茫月 2020-12-15 18:42

I\'ve been working on this for about an hour and looked at all related SO questions.

My problem is very simple:

I have HomePageVieModel:

Home         


        
7条回答
  •  自闭症患者
    2020-12-15 19:19

    The answer from @Darren works well in most cases, and should be the preferred method if possible. However, it is not a working solution where the following (niche) conditions all occur:

    • DataGrid with DataGridTemplateColumn
    • .NET 4
    • Windows XP

    ...and possibly in other circumstances too. In theory it should fail on all versions of Windows; but in my experience the ElementName approach works in a DataGrid on Windows 7 upwards but not XP.

    In the following fictional example, we are trying to bind to an ICommand called ShowThingCommand on the UserControl.DataContext (which is the ViewModel):

    
        
            
                
                    
                        
                            

    Due to the DataTemplate not being in the same VisualTree as the main control, it's not possible to reference back up to the control by ElementName.

    To solve this, the little known .NET 4 and above {x:Reference} can be used. Modifying the above example:

    
        
            
                
                    
                        
                            

    For reference, see the following stackoverflow posts:

    Question 19244111

    Question 5834336

    ...and for an explanation of why ElementName doesn't work in this circumstance, see this blog post which contains a pre-.NET 4 workaround.

提交回复
热议问题