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

posted @ 2017-02-03 10:21  赵御辩  阅读(2087)  评论(0编辑  收藏  举报