Duy Thuận Võ
Duy Thuận Võ

Reputation: 29

PropertyChanged is null when property is set via object

So I'm doing some example with data binding in C# winforms. And the textbox's text does not change when I update values of the object contains that property, but when I used another textbox to directly change the value of the property then it works well. I found out that when I used another textbox to set value, the "PropertyChanged" has value and when I used object, it's just "null".

Here are my class:

public WeatherClient() { }
        ~WeatherClient() { }
        public void Dispose() { }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        //other properties
        private float _generationtime_ms;
        public float generationtime_ms
        {
            get => _generationtime_ms;
            set
            {
                _generationtime_ms = value;
                OnPropertyChanged(nameof(this.generationtime_ms));
            }
        }
        public WeatherClient getWeather(string url)
        {
            using (WebClient web = new WebClient())
            {
                url = string.Format(url);
                var json = web.DownloadString(url);
                WeatherClient WeatherInfoRespond = JsonConvert.DeserializeObject<WeatherClient>(json);
                return WeatherInfoRespond;
            }
        }

Form.cs:

        WeatherClient WeatherClient = new WeatherClient();
public Form1()
        {
            InitializeComponent();

            WeatherClient = WeatherClient.getWeather(); //this for avoiding null value of class type variable
            BindingInit();
        }

Binding WeatherClient.generationtime_ms with textbox3

void BindingInit()
        {
            Binding Binding2 = new Binding("Text", WeatherClient, nameof(WeatherClient.generationtime_ms), true, DataSourceUpdateMode.OnPropertyChanged);
            textBox3.DataBindings.Add(Binding2);
        }

When I update via instance, it does not binding:

       private void button1_Click(object sender, EventArgs e)
        {
            WeatherClient = WeatherClient.getWeather();
        }

And when I used another textbox to update value, it works:

 private void button1_Click(object sender, EventArgs e)
        {
            WeatherClient.generationtime_ms = Convert.ToInt32(textBox1.Text);
        }

Any suggestion would help. Thank you guys.

Upvotes: 0

Views: 156

Answers (0)

Related Questions