INotifyPropertyChanged in UserControl

后端 未结 3 1634
傲寒
傲寒 2021-02-19 17:36

I have a custom control which is inherited from TextBox control. I would like to implement the INotifyPropertyChanged interface in my custom control.



        
3条回答
  •  醉梦人生
    2021-02-19 18:23

    Do it like I said in the comments. It doesnt work like you did. Just create an extra class and implement Notification Interface there and apply this class to the DataContext of the UserControl. And it will work like you need.

     public partial class W3 : UserControl
        {
            WeatherViewModel model = new WeatherViewModel();
    
            public W3()
            {
                InitializeComponent();
                this.DataContext = model;
            }
    
            public void UpdateUI(List data, bool isNextDays)
            {
                model.UpdateUI(data, isNextDays);
            }
        }
    
        class WeatherViewModel : INotifyPropertyChanged
        {     
    
            public void UpdateUI(List data, bool isNextDays)
            {
                List weatherInfo = data;
                if (weatherInfo.Count != 0)
                {
                    CurrentWeather = weatherInfo.First();
                    if (isNextDays)
                        Forecast = weatherInfo.Skip(1).ToList();
                }
            }
    
            private List _forecast = new List();
    
            public List Forecast
            {
                get { return _forecast; }
                set
                {
                    _forecast = value;
                    OnPropertyChanged("Forecast");
                }
            }
    
            private WeatherDetails _currentWeather = new WeatherDetails();
    
            public WeatherDetails CurrentWeather
            {
                get { return _currentWeather; }
                set
                {
                    _currentWeather = value;
                    OnPropertyChanged("CurrentWeather");
                }
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            private void OnPropertyChanged(string propertyName)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    

提交回复
热议问题