将依赖属性绑定到代码隐藏中的另一个依赖属性

时间:2021-05-12 15:17:46

标签: c# wpf

我有一个名为 My_A_Control 的控件,它有一个名为 Subject 的属性

public class My_A_Control : Control

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

并且我有另一个名为 My_B_Control 的控件,它在其模板中使用了 My_A_Control

所以我想通过My_B_Control改变My_A_Control中subject的值

我首先在 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); }
        }

然后我按如下方式连接它们

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

但是这个方法不行

更新:

 <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>
...

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

更新2: 此代码有效

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);

1 个答案:

答案 0 :(得分:3)

这样的事情应该可以工作:

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;
}