Simple Binding of Data from code behind to XAML

前端 未结 1 1018
逝去的感伤
逝去的感伤 2021-01-21 23:40


I am new to WPF concepts. I want to just display a string in a textbox. I tried the following C# code and XAML to bind a string to a TextBox.Text property. C# code:

1条回答
  •  隐瞒了意图╮
    2021-01-22 00:24

    Databinding does not work with fields. Use Properties instead:

    public int TmpVal {get; set;}
    public string TmpStr {get; set;}
    

    Also if you want the textbox to automatically pick up changes from your data you would ideally need to implement INotifyPropertyChanged or make it a dependency property or have a XXXChanged event for each XXX property (this doesn't work anymore).

    
        
            
            
        
    
    

    And the code behind:

    public partial class Window1 : Window, INotifyPropertyChanged
    {
        public Window1()
        {
            this.TmpStr = "Windows Created";
            this.InitializeComponent();
            this.DataContext = this;
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        public string TmpStr { get; set; }
    
        public int TmpVal { get; set; }
    
        private void viewButton_Click(object sender, RoutedEventArgs args)
        {
            this.TmpStr = "Button clicked";
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs("TmpStr"));
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题