如何在属性上实现双向绑定?

我知道有很多关于依赖属性的问题,我已经看了很多,但是它们似乎都没有解决我的问题。

我有一个像这样的窗口:

      

其中MyTextValue只是一个字符串属性,通知何时更改:

  private string _myTextValue = "Totally different value"; public string MyTextValue { get { return _myTextValue; } set { _myTextValue = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } 

TextInputWrapper也很简单:

    

代码隐藏:

 public partial class TextInputWrapper : UserControl { public static readonly DependencyProperty MyTextProperty = DependencyProperty.Register("MyText", typeof(string), typeof(TextInputWrapper), new PropertyMetadata("Empty")); public TextInputWrapper() { InitializeComponent(); } public string MyText { get { return (string)GetValue(MyTextProperty); } set { SetValue(MyTextProperty, value); } } } 

现在据我所知,我的Window现在应该有2个TextBox控件,它们彼此绑定。 如果我在一个中更改值,则另一个应该更新。

但是,我最终得到了2个单独的TextBoxes,其中第一个以文本“Empty”开头,而下一个文本块的文本“Totally different value”。 像这样: 截图

并且更改其中任何一个的文本都不会在另一个中重现。

我希望它们都以文本“完全不同的值”开始并与它们的值同步(通过将更改传播到MainWindow上的MyTextValue属性,并通过在那里通知更改,然后更改将传播到另一个文本框)。 在我的控件中正确实现数据绑定我错过了什么?

删除作业

 DataContext="{Binding RelativeSource={RelativeSource Self}}" 

来自UserControl的XAML。 而是将“内部”绑定的RelativeSource设置为控件实例:

    

显式设置UserControl的DataContext可防止从其父控件inheritanceDataContext,即像Binding一样

  

将使用UserControl作为源对象,而不是当前的DataContext。


作为一般规则, 从不显式设置UserControl的DataContext。

尝试更改此行:

 public static readonly DependencyProperty MyTextProperty = DependencyProperty.Register("MyText", typeof(string), typeof(TextInputWrapper), new PropertyMetadata("Empty")); 

对此:

 public static readonly DependencyProperty MyTextProperty = DependencyProperty.Register("MyText", typeof(string), typeof(TextInputWrapper), new FrameworkPropertyMetadata("Empty", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));