当前位置:首页 > Windows程序 > 正文

new PropertyChangedEventArgs("Item[]"));}}public event Prop

2024-03-31 Windows程序

当用到dictionary<key,value>来储存数据的时候,有时候需要在界面上绑定一个key来显示value,这时候有两种思路:

一种是写一个自界说的扩展类,类似Binding,这里取名为“MyBinding”,在binding类内部实现key的绑定。

另一种更简洁,更通用的要领是用索引实现绑定。属性能够绑定到界面,,同样的索引也能绑定到界面。

实现代码如下:

1.自界说MarkupExtension,

using System; using System.Windows.Data; using System.Windows.Markup; namespace 索引绑定 { public class MyBinding : MarkupExtension { public int key { get; set; } public override object ProvideValue(IServiceProvider serviceProvider) { var b = new Binding("Value"); b.Source = ViewModelNomal.Instance.li[key]; return b.ProvideValue(serviceProvider); } } }

  2.索引绑定

public class ModelUseIndexer : INotifyPropertyChanged { private readonly Dictionary<int, int> _localDictionary = new Dictionary<int, int> (); [IndexerName("Item")] public int this[int index] { get { int result; _localDictionary.TryGetValue(index, out result); return result; } set { if (_localDictionary.ContainsKey(index)) _localDictionary[index] = value; else _localDictionary.Add(index, value); if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Item[]")); } } public event PropertyChangedEventHandler PropertyChanged; }

  

运行效果是一样的,但索引绑定依赖代码性更少,更切合oop的思想。

技术分享图片

源码地点:https://files.cnblogs.com/files/lizhijian/%E7%B4%A2%E5%BC%95%E7%BB%91%E5%AE%9A.rar

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/35045.html

Jm-杰米博客Jamie
草根站长的技术交流乐园!IT不会不要紧快来好好学习吧!
  • 20786文章总数
  • 7494590访问次数
  • 建站天数
  • 友情链接