Usercontrol using wrong Datacontext

前端 未结 4 1129
别跟我提以往
别跟我提以往 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:

    <Window.Resources>
        <DataTemplate DataType="{x:Type vm:TranslationTextInputViewModel}">
            <Views:TranslationTextInput />
        </DataTemplate>
    </Window.Resources>
    

    or this:

    <Views:TranslationTextInput 
        DataContext="{Binding SelectedTranslationTextInputViewModel}" />
    

    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.

    0 讨论(0)
  • 2021-01-24 11:46

    Try this:

    <Views:TranslationTextInput  Translation="{Binding SelectedEntity.Name}" DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" /> 
    
    0 讨论(0)
  • 2021-01-24 11:51

    Once you set the DataContext your bindings will use it, so I would expect this behaviour -- looking for SelectedEntity.Name on the TranslationTextInputViewModel.

    There are a few ways to get this working. Personally, I like to model these relationships in the view-models themselves (view-models with view-model properties), but in this situation I'd probably try this, as unpleasant as it feels:

    <Views:TranslationTextInput 
        Translation="{Binding DataContext.SelectedEntity.Name,
                      RelativeSource={RelativeSource FindAncestor,
                                      AncestorType=ParentControlType}}" />
    
    0 讨论(0)
  • 2021-01-24 12:01

    This is because you set the TranslationTextInput.DataContext to TranslationTextInputViewModel in the constructor.

    0 讨论(0)
提交回复
热议问题