zoukankan      html  css  js  c++  java
  • WPF绑定之索引器值变化通知

    背景

    在某些应用中,需要在界面上绑定到索引器,并在值发生变化时实时更新。

    解决方案

    只要将包含索引器的类实现INotifyPropertyChanged接口,并在索引值更改时引发PropertyChanged事件,并将属性名称设置为Item[]即可。示例代码如下:

    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
    
    }

    在 代码中,Binding.IndexerName是一个常量,值即为Item[]。

    原理

    本质上,索引器也是属性,即有参属性。

    在WPF的绑定系统中,会监听属性更改事件,如果变化的属性名称为Item[]而且绑定的是索引器,则会更新界面值。可以看出,这个过程与索引器实际名称无关系。所以,即使是在索引器上使用IndexerNameAttribute显式更改索引器名称也不影响整个过程。

    无参属性绑定冷知识

    在WPF绑定系统中,会监听属性更改事件。但是如果绑定的属性为无参属性(即正常属性,非索引器),其与变化的属性名称比较是不区分大小写的。所以在下面的代码中

    private string _name;
    
    public string Name
    {
        get { return this._name; }
        set
        {
            if (_name != value)
            {
                _name = value;
                this.OnPropertyChanged("naMe");
            }
        }
    }

    name、Name、naMe、naME效果是一样的。

    代码下载

    博客园:NotifyDictionaryDemo

  • 相关阅读:
    【Oracle11g】06_网络配置
    【Python3 爬虫】U20_正则表达式爬取古诗文网
    【Oracle11g】05_完整性约束
    【Python3 爬虫】U19_正则表达式之re模块其他函数
    【Python3 爬虫】U18_正则表达式之group分组
    【Python3 爬虫】U17_正则表达式之转义字符和原生字符
    【Python3 爬虫】U16_正则表达式之开始结束和或语法
    常见的概率分布
    广义线性模型
    gamma函数及相关其分布
  • 原文地址:https://www.cnblogs.com/yiyan127/p/WPF-NotifyIndexer.html
Copyright © 2011-2022 走看看