Problem with WPF Data Binding Defined in Code Not Updating UI Elements

前端 未结 6 743
天涯浪人
天涯浪人 2021-02-08 22:51

I need to define new UI Elements as well as data binding in code because they will be implemented after run-time. Here is a simplified version of what I am trying to do.

6条回答
  •  攒了一身酷
    2021-02-08 23:38

    I've just cut+pasted your code (and added a little), and it works fine for me:

        public Window1()
        {
            InitializeComponent();
    
            AddressBook book = new AddressBook();
            book.HouseNumber = 123;
            TextBlock tb = new TextBlock();
            Binding bind = new Binding("HouseNumber");
            bind.Source = book;
            bind.Mode = BindingMode.OneWay;
            tb.SetBinding(TextBlock.TextProperty, bind); // Text block displays "123"
            myGrid.Children.Add(tb);
            book.HouseNumber = 456; 
        }
    
        private void TestButton_Click(object sender, RoutedEventArgs e)
        {
            AddressBook book = 
               (AddressBook(TextBlock)
                  myGrid.Children[0])
                  .GetBindingExpression(TextBlock.TextProperty)
                  .DataItem;
    
            book.HouseNumber++;
        }
    

    Displays 456 on startup, clicking the button makes the number in the TextBlock increment just fine.

    Perhaps you are looking in the wrong place for the cause of the problem?

提交回复
热议问题