You seem to be somewhat confused with a few things. If you want to set your view model as the UserControl.DataContext
in XAML, that is ok, but you don't data bind to controls from there:
<UserControl.DataContext>
<local:VM />
</UserControl.DataContext>
Next, if the view model is set as the UserControl.DataContext
, then you can access its properties from the XAML in the UserControl
like this:
<StackPanel>
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Text="{Binding Length}"/>
</StackPanel>
Now if you want to access the ControlText
property from the XAML, then that is when you need to use the RelativeSource Binding
. However, notice how you should reference your UserControl
, by its name/type and not using UserControl
because as your error says, there is no ControlText
property defined in UserControl
. Try this:
<StackPanel>
<TextBox Text="{Binding ControlText, RelativeSource={RelativeSource
AncestorType={x:Type local:YourUserControl}} />
<TextBlock Text="{Binding Length}"/>
</StackPanel>
Finally, if you want to data bind to the ControlText
property of your control from outside the control, then you could do that like this:
<local:YourUserControl ControlText="{Binding SomeStringProperty}" />
UPDATE >>>
When using MVVM, we generally don't try to pass data from one data source through a UIElement
to another data source. Instead, we prefer to pass the data from one data item to another data item. Your problem is that you are instantiating your view model in the view... instead, instantiate it in a parent view model and pass in whatever values you want and then set it as the UserControl.DataContext
property value from outside the control in the parent view:
<local:YourUserControl DataContext="{Binding YourChildViewModelPropertyInParentVM}" />
Once you have the correct values in the view model, then you shouldn't need the ControlText
property.