简体   繁体   中英

Binding programmatically doesn't work when I add the controls in run-time

I have two TextBoxes and I want to bind between their Visibility property in run time,

The binding works when I add the TextBoxes by Xaml but doesn't work when I add them programmatically,

Any help !!

    public partial class Window1 : Window
    {
        TextBox txt1 = new TextBox();
        TextBox txt2 = new TextBox();
        public Window1()
        {
            InitializeComponent();

            txt1.Name = "txt1";
            txt1.Margin= new Thickness(30,0,128,0);
            txt1.VerticalAlignment = VerticalAlignment.Top;

            txt2.Name = "txt2";
            txt2.Margin = new Thickness(30, 32, 128, 0);
            txt2.VerticalAlignment = VerticalAlignment.Top;

            Binding binding = new Binding();
            binding.ElementName = "txt1";
            binding.Path = new PropertyPath(TextBox.VisibilityProperty);
            BindingOperations.SetBinding(txt2, TextBox.VisibilityProperty, binding);


            grid.Children.Add(txt1);
            grid.Children.Add(txt2);
        }
    }

Thanks in advance

UPDATED

Instead of setting the ElementName property, just set the Source property for the Binding to the Element object you wish to bind to.

TextBox txt1 = new TextBox();
TextBox txt2 = new TextBox();

public Window1()
{
   InitializeComponent();

   txt1.Name = "txt1";
   txt1.Margin = new Thickness(30, 0, 128, 0);
   txt1.VerticalAlignment = VerticalAlignment.Top;
   txt1.Visibility = Visibility.Visible;

   txt2.Name = "txt2";
   txt2.Margin = new Thickness(30, 32, 128, 0);
   txt2.VerticalAlignment = VerticalAlignment.Top;

   Binding binding = new Binding();
   binding.Source = txt1; // set the source object instead of ElementName
   binding.Path = new PropertyPath(TextBox.VisibilityProperty);
   BindingOperations.SetBinding(txt2, TextBox.VisibilityProperty, binding);

   grid.Children.Add(txt1);
   grid.Children.Add(txt2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM