WPF usercontrol Twoway binding Dependency Property
Bind the TextBox.Text
property in the UserControl to its SampleProperty
like this:
<TextBox Text="{Binding SampleProperty,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
Now you could simply remove your OnSamplePropertyChanged
callback.
You might also register SampleProperty
to bind two-way by default like this:
public static readonly DependencyProperty
SamplePropertyProperty = DependencyProperty.Register(
"SampleProperty", typeof(string), typeof(UserControl1),
new FrameworkPropertyMetadata(
null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
An alternative way to do this is an ElementName Binding. First assign the x:Name
attribute to the UserControl (for example x:Name="MyUC"
), then change the binding to:
<TextBox Text="{Binding ElementName=MyUC, Path=SampleProperty}"/>