How to use command bindings in user controls in wpf?

前端 未结 2 578
一个人的身影
一个人的身影 2021-02-04 16:13

In MainWindow the commandbinding works fine. In UserControl1 it doesnt work. Note the datacontext is set correctly as is evidenced by the content of the button which is the res

2条回答
  •  情话喂你
    2021-02-04 16:23

    Here I am AGAIN almost two years after I posted this. I forgot about this little feature of WPF and sure enough it bit me again.

    The answer marked above is partially correct but contains other content that is distracting and/or incorrect. For clarity I will highlight what the problem is and what the solution is. I'm doing this more for my benefit than yours because I'm sure I'll be back here in about sixteen months.

    Here is the problem. Don't do this. Your bindings will all continue to work except for your routed commands:

    
    
        
            
        
    

    The solution is use relative source in setting the data context as follows:

    
        
    
    

    The only answer to the problem I asked about is the one above (there may in fact be other answers but they are not discussed thus far in this question). Specifically: Setting "DataContext = this" in the usercontrol is NOT a solution and will in fact break bindings in the control that hosts the user control. Also, only properties that are the targets of bindings must be dependency properties. That suggestion is incorrect .

提交回复
热议问题