I know there are lots of questions about dependency properties, and I have looked at many of them, but none of them seems to solve my problem.
I have a Window like t
Remove the assignment
DataContext="{Binding RelativeSource={RelativeSource Self}}"
from the UserControl's XAML. Instead, set the RelativeSource
of the "internal" binding to the control instance:
<UserControl x:Class="WpfBindingTest.TextInputWrapper" ...>
<TextBox Text="{Binding MyText,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</UserControl>
Explicitly setting the DataContext of a UserControl prevents inheriting the DataContext from its parent control, i.e. a Binding like
<local:TextInputWrapper MyText="{Binding MyTextValue, Mode=TwoWay}" />
would use the UserControl as source object, instead of the current DataContext.
As a general rule, never explicitly set the DataContext of a UserControl.
Try changing this line:
public static readonly DependencyProperty MyTextProperty = DependencyProperty.Register("MyText",
typeof(string), typeof(TextInputWrapper), new PropertyMetadata("Empty"));
To this:
public static readonly DependencyProperty MyTextProperty = DependencyProperty.Register("MyText",
typeof(string), typeof(TextInputWrapper), new FrameworkPropertyMetadata("Empty", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));