PropertyChanged for indexer property

后端 未结 4 570
天命终不由人
天命终不由人 2020-12-01 04:11

I have a class with an indexer property, with a string key:

public class IndexerProvider {
    public object this[string key] {
        get
        {
                


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 04:59

    There are at least a couple of additional caveats when dealing with INotifyPropertyChang(ed/ing) and indexers.

    The first is that most of the popular methods of avoiding magic property name strings are ineffective. The string created by the [CallerMemberName] attribute is missing the '[]' at the end, and lambda member expressions have problems expressing the concept at all.

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

    Several other posts have used Binding.IndexerName to avoid the string literal "Item[]", which is reasonable, but raises the second potential issue. An investigation of the dissasembly of related parts of WPF turned up the following segment in 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[]";
      }
    

    The repeated use of "Item[]" as a constant value suggests that WPF is expecting that to be the name passed in the PropertyChanged event, and, even if it doesn't care what the actual property is called (which I didn't determine to my satisfaction one way or the other), avoiding use of [IndexerName] would maintain consistency.

提交回复
热议问题