There is some generic class

public class GenericClass<T> { public object this[string s] { return s; } } 

Well, an instance of the class is used as a DataContext. Then to call from xaml there will be such a markup.

 <TextBlock Text="{Binding [qwer]}"/> 

and it will return the text "qwer".

The question is, is it possible to get rid of square brackets with any tricks? There is a class DataView, how is it implemented there?

  • And why do you need to get rid of square brackets? Is this part of a task or just wondering how it was done in a DataView (by the way, never used for some reason)? - VladD
  • It is possible to get rid, to turn out usual binding on property. - Monk
  • @Monk, only there is no such property. - iRumba
  • @VladD so that it can be used, for example, in elements where there is a property of type DisplayMemberPath . - iRumba
  • @iRumba I incorrectly put it - if you get rid of the brackets, then this will be the syntax of the usual binding. - Monk

1 answer 1

Found a solution. The class public class GenericClass<T> must inherit the ICustomTypeDescriptor interface and does not need an indexer in it at all. Then I need from the constructor to simply select the transmitted object of type Т and use it as a resource for implementing the interface.


I will not put the verbatim code, because I do not have it at hand. I can only from memory to sketch its basis

Class:

 public class ViewModel<T>: ICustomTypeDescriptor { T _source; public ViewModel(T obj) { _source = obj; } // далее идет реализация интерфейса. Все методы сделаны идентично, я приведу пример одного public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(_source); } } 

The class is not ready yet. You also need to inherit INotifyPropertyChanged and provide for monitoring model properties or other ways of changing properties from code. But that's another story altogether)

  • one
    Code would add. - andreycha
  • one
    Perfect solution! I support the previous speaker - your answer lacks an example with a code. - VladD 4:02 pm