Notification of changes in the value of the indexer bound to WPF, and notification of index binding to wpf
Background
In some applications, You need to bind to the indexer on the interface and update the value in real time when the value changes.
Solution
You only need to implement the INotifyPropertyChanged interface for Classes containing the indexer, trigger the PropertyChanged event when the index value is changed, and set the attribute name to Item. The sample code is as follows:
public class NotifyDictionary : INotifyPropertyChanged{ private readonly Dictionary<string, string> _dictionary = new Dictionary<string, string>(); public string this[string index] { get { if (_dictionary.ContainsKey(index)) { return _dictionary[index]; } return string.Empty; } set { string oldValue = string.Empty; if (_dictionary.ContainsKey(index)) { oldValue = _dictionary[index]; } _dictionary[index] = value; if (oldValue != value) { OnPropertyChanged(Binding.IndexerName); } } } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion INotifyPropertyChanged}
In the code, Binding. IndexerName is a constant and its value is Item [].
Principle
Essentially, the indexer is also an attribute, that is, a parameter attribute.
In the WPF binding system, the property change event is monitored. If the changed property name is Item [] and the index is bound, the interface value is updated. It can be seen that this process has nothing to do with the actual name of the indexer. Therefore, using IndexerNameAttribute to explicitly change the name of the indexer does not affect the entire process.
No parameter property binding cold knowledge
In the WPF binding system, the property change event is monitored. However, if the bound property is a non-parameter property (that is, a normal property, non-indexer), it is case insensitive to the changed property name. So in the following code
private string _name;public string Name{ get { return this._name; } set { if (_name != value) { _name = value; this.OnPropertyChanged("naMe"); } }}
The effects of name, Name, naMe are the same.
Code download
Blog: yydictionarydemo