user13024846
user13024846

Reputation:

bind Dependency Property to Another Dependency Property in Code Behind

I have a Control Called My_A_Control and it has a property called Subject

public class My_A_Control : Control

public static readonly DependencyProperty SubjectProperty = DependencyProperty.Register(
         "Subject", typeof(string), typeof(My_A_Control), new PropertyMetadata(Confirm);

and i have another control called My_B_Control that Inside its template, My_A_Control is used

So I want to change the value of the subject in My_A_Control through My_B_Control

I first created a property as follows in My_B_Control

public class My_B_Control : Control

public static readonly DependencyProperty SubjectProperty =
           My_A_Control.SubjectProperty.AddOwner(typeof(My_B_Control));

        public string Subject
        {
            get { return (string) GetValue(SubjectProperty); }
            set { SetValue(SubjectProperty, value); }
        }

And then I connected them as follows

public My_B_Control()
{
  var ctl = new My_A_Control
   {
     Subject = Subject
   };
}

But this method does not work

update:

 <Style TargetType="local:My_B_Control">
                <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:My_B_Control">
                    <Border x:Name="templateRoot" Background="{TemplateBinding Background}">
                        <Grid x:Name="PART_Root" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="30"/>
                            </Grid.ColumnDefinitions>
                            <Popup Grid.Column="0" VerticalOffset="4" x:Name="PART_Popup" StaysOpen="False"/>
                        </Grid>
...

and

public My_B_Control()
    {
      var ctl = new My_A_Control
       {
         Subject = Subject
       };
 _popup.Child = ctl;
    }

update 2: this code work

Binding myBinding = new Binding();
            myBinding.Source = this;
            myBinding.Path = new PropertyPath("Subject");
            myBinding.Mode = BindingMode.TwoWay;
            myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            BindingOperations.SetBinding(ctl, My_A_Control.SubjectProperty, myBinding);

Upvotes: 1

Views: 849

Answers (1)

Clemens
Clemens

Reputation: 128157

Something like this should work:

public My_B_Control()
{
     var ctl = new My_A_Control();

     ctl.SetBinding(My_A_Control.SubjectProperty, new Binding
     {
         Path = new PropertyPath("Subject"),
         Source = this
     });

     _popup.Child = ctl;
}

Upvotes: 3

Related Questions