INotifyPropertyChanged in UserControl

后端 未结 3 754
[愿得一人]
[愿得一人] 2021-02-19 17:32

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:22

    The PropertyChanged event is used by UI code, but not in that sense you are writing. Controls never implement INPC (short for INotifyPropertyChanged), they are bound to object that have implemented INPC. This way certain UI properties, e.g. the Text property on the TextBox control is bound to a property on such class. This is the basis of MVVM architecture.

    Example, you would write the following XAML code:

    
    

    And you set the data context for TextBlock (or any of its ancestors, DataContext is propagated) in the code in the following manner:

    txtBox.DataContext = new Movie {Title = "Titanic"};
    

    And now for the class itself:

    public class Movie : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(string info)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    
        private string _title;
        public string Title
        {
            get { return _title; }
            set
            {
                if (_title == value) return;
    
                _title = value;
                NotifyPropertyChanged("Title");
            }
        }
    }
    

    Now, whenever you change the Title property, whether in the code or via other binding, UI will be automatically refreshed. Here's more information about Data Binding and MVVM.

提交回复
热议问题