开发者

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();
            bindi开发者_如何学JAVAng.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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜