Usercontrol using wrong Datacontext

筅森魡賤 提交于 2019-12-02 03:17:53

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.

Try this:

<Views:TranslationTextInput  Translation="{Binding SelectedEntity.Name}" DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" /> 

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}}" />

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!