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

前端 未结 6 738
天涯浪人
天涯浪人 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:26

    Make sure you're updating the AddressBook reference that was used in the binding, and not some other AddressBook reference.

    I got the following to work with the AddressBook code you gave.

    
        
        
        
    
    

    Code behind:

    public partial class Window1 : Window
    {
        private AddressBook book;
    
        public Window1()
        {
            InitializeComponent();
    
            book = new AddressBook();
            book.HouseNumber = 13;
    
            TextBlock tb = new TextBlock();
            Binding bind = new Binding("HouseNumber");
            bind.Source = book;
            tb.SetBinding(TextBlock.TextProperty, bind);
            myGrid.Children.Add(tb);
        }
    
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Random rnd = new Random();
            book.HouseNumber = rnd.Next();
        }
    }
    

    Note the same reference is used in the update code.

提交回复
热议问题