zoukankan      html  css  js  c++  java
  • WPF中,多key值绑定问题,一个key绑定一个界面上的对象

    问题说明:

    当用到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

    谢谢阅读,希望可以帮助到你。

  • 相关阅读:
    C++ 数组array与vector的比较
    C/C++头文件区别
    C/C++ 标准输入输出重定向
    C文件读写
    输入输出重定向
    【剑指offer26 二叉搜索树与双向链表】
    【剑指offer25 复杂链表的复制】
    【剑指offer23 二叉搜索树的后序遍历序列】
    【剑指offer22 从上往下打印二叉树 & 60 把二叉树打印成多行】
    【剑指offer21 栈的压入、弹出序列】
  • 原文地址:https://www.cnblogs.com/congqiandehoulai/p/8367714.html
Copyright © 2011-2022 走看看