I have a UserControl that is used in a parent control in this way:
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.