代码之家  ›  专栏  ›  技术社区  ›  Inferis

已更改索引器属性的属性

  •  33
  • Inferis  · 技术社区  · 17 年前

    我有一个具有索引器属性和字符串键的类:

    public class IndexerProvider {
        public object this[string key] {
            get
            {
                return ...
            }
            set
            {
                ...
            }
        }
    
        ...
    }
    

    我使用索引器表示法绑定到WPF中该类的一个实例:

    <TextBox Text="{Binding [IndexerKeyThingy]}">
    

    PropertyChanged 当其中一个索引器值更改时发生。我尝试使用属性名“[keyname]”(即在键名周围包含[])来提升它,但这似乎不起作用。我的输出窗口中没有任何绑定错误。

    我不能使用CollectionChangedEvent,因为索引不是基于整数的。从技术上讲,这个对象不是一个集合。

    4 回复  |  直到 17 年前
        1
  •  52
  •   Jb Evain    17 年前

    this blog entry ,你必须使用 "Item[]" . 项是编译器在使用索引器时生成的属性的名称。

    如果希望显式,可以使用 IndexerName 属性

    这将使代码看起来像:

    public class IndexerProvider : INotifyPropertyChanged {
    
        [IndexerName ("Item")]
        public object this [string key] {
            get {
                return ...;
            }
            set {
                ... = value;
                FirePropertyChanged ("Item[]");
            }
        }
    }
    

    至少它使意图更加明确。但是,如果你的好友发现了字符串,我不建议你更改索引器的名称 “项目[]” 硬编码,这可能意味着WPF将无法处理不同的索引器名称。

        2
  •  16
  •   ghord    15 年前

    此外,您还可以使用

    FirePropertyChanged ("Item[IndexerKeyThingy]");
    

    仅通知绑定到索引器上的IndexerKeyThingy的控件。

        3
  •  6
  •   Andrew Elford    12 年前

    在处理INotifyPropertyChang(ed/ing)和索引器时,至少还有几个额外的注意事项。

    第一个是大多数 popular methods 避免使用魔法属性名称字符串的方法无效。由 [CallerMemberName] 属性结尾缺少“[]”,lambda成员表达式在表达该概念时遇到问题。

    () => this[]  //Is invalid
    () => this[i] //Is a method call expression on get_Item(TIndex i)
    () => this    //Is a constant expression on the base object
    

    几个 other posts Binding.IndexerName 避免使用字符串文字 "Item[]" ,这是合理的,但提出了第二个潜在问题。对WPF相关部分分解的调查在PropertyPath.ResolvePathParts中发现了以下部分。

    if (this._arySVI[i].type == SourceValueType.Indexer)
      {
        IndexerParameterInfo[] array = this.ResolveIndexerParams(this._arySVI[i].paramList, obj, throwOnError);
        this._earlyBoundPathParts[i] = array;
        this._arySVI[i].propertyName = "Item[]";
      }
    

    重复使用 “项目[]” 作为一个常量值,WPF希望它是PropertyChanged事件中传递的名称,并且,即使它不关心实际属性的调用(我没有以某种方式满意地确定),也避免使用 [IndexerName] 将保持一致性。

        4
  •  5
  •   dimondwoof    16 年前

    public class IndexerProvider : INotifyPropertyChanged {
    
        [IndexerName("myIndexItem")]
        public object this [string key] {
            get {
                return ...;
            }
            set {
                ... = value;
                FirePropertyChanged ("myIndexItem[]");
            }
        }
    }
    

    将索引器名称设置为所需的名称后,就可以在FirePropertyChanged事件中使用它。