WPF中,多key值綁定問題,一個key綁定一個界面上的對象
阿新 • • 發佈:2018-01-28
eval vid sha 實現 notify name har 內部實現 arp
問題說明:
當用到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
謝謝閱讀,希望可以幫助到你。
WPF中,多key值綁定問題,一個key綁定一個界面上的對象