0

How can I make a two way binding in code behind between one dependency property in window and another one in a UserControl, so that when user action in one will update the DP in another

public partial class MyWindow
{
    public MyWindow()
    {    
        InitializeComponent();
        var myControl = new MyControl();
        this.SetBinding(MyWindow.CurrentPathProperty, new Binding
        {
            Source = myControl.CurrentPath
        });
    }

    public string CurrentPath
    {
        get { return (string)GetValue(CurrentPathProperty); }       
        set { SetValue(CurrentPathProperty, value); }
    }

    public static readonly DependencyProperty CurrentPathProperty =
            DependencyProperty.Register("CurrentPath", typeof(string),
            typeof(MyWindow), new PropertyMetadata(OnPathChanged)); 
}

public partial class MyControl : UserControl
{
    public string CurrentPath
    {
        get { return (string)GetValue(CurrentPathProperty); }       
        set { SetValue(CurrentPathProperty, value); }
    }

    public static readonly DependencyProperty CurrentPathProperty =
            DependencyProperty.Register("CurrentPath", typeof(string),
            typeof(MyControl), new PropertyMetadata(OnPathChanged));

}
Daniel
  • 1,064
  • 2
  • 13
  • 30
  • `Source = myControl, Path = new PropertyPath("CurrentPath"), Mode = BindingMode.TwoWay` – Clemens May 17 '20 at 17:33
  • @Clemens That was it, thank you! Can you please make it as answer so I can accept and close the question – Daniel May 17 '20 at 17:52
  • @Clemens The proposed existing answer is not the same as that one uses Properties and INotifyPropertyChanged – Daniel May 17 '20 at 18:02
  • That makes no difference at all. It doesn't matter if the source property is a dependency property or an ordinary CLR property. The Binding is identical. – Clemens May 17 '20 at 18:02

0 Answers0