Usercontrol using wrong Datacontext

前端 未结 4 1138
别跟我提以往
别跟我提以往 2021-01-24 11:23

I have a UserControl that is used in a parent control in this way:


         


        
4条回答
  •  旧巷少年郎
    2021-01-24 11:35

    You really shouldn't ever set the DataContext of a UserControl from inside the UserControl. By doing so, you are preventing any other DataContext from getting passed to the UserControl, which kind of defeats one of WPF's biggest advantages of having separate UI and data layers.

    When your UserControl is being created, you are setting the DataContext to a new TranslationTextInputViewModel, and TranslationTextInputViewModel does not have a property called SelectedEntity, so your binding fails.

    My suggestion? Don't set the DataContext in the UserControl.

    If you want a specific ViewModel to be used for a specific UserControl, add that to your ParentViewModel and pass it in as the DataContext, such as this:

    
        
            
        
    
    

    or this:

    
    

    Or if your ViewModel contains functionality specific to the UserControl itself and should not be part of your application layer, put that code in the code-behind the UserControl and get rid of the ViewModel altogether.

提交回复
热议问题