Bind a label to a “variable”

后端 未结 4 1043
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 05:02

Say I have a global variable INT named X. Since X is global, we can assume that anything can modify its value so it is being changed everytime.

Say I have a Label co

4条回答
  •  有刺的猬
    2020-12-05 05:24

    If you want to use the Databinding infrastructure, and reflect the changes made to a value, you need a way to notify the UI about the changes made to the binding value.

    So the best way to do that is to use a property and implement the INotifyPropertyChanged interface, like this:

    class frmFoo : Form, INotifyPropertyChanged
    {        
        private string _foo;
    
        public string Foo
        {
            get { return _foo; }
            set
            {
                _foo = value;
                OnPropertyChanged("Foo");
            }
        }
    
        protected virtual void OnPropertyChanged(string property)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    
        #region INotifyPropertyChanged Members
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        #endregion
    }
    

    Also remember that you need to setup the binding on the label first:

    public frmFoo()
    {
        InitializeComponent();
        lblTest.DataBindings.Add(new Binding("Text", this, "Foo"));
    }
    

提交回复
热议问题