c# – How to use indexers in xaml without square brackets?

Question:

There is a generic class

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

Well, the instance of the class is used as DataContext. Then for a call from xaml there will be such 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 some tricks? There is a DataView class, how is it implemented there?

Answer:

Found a solution. The public class GenericClass<T> must inherit the ICustomTypeDescriptor interface and do not need an indexer at all. Then I just need to pick up the passed object of type Т from the constructor and use it as a resource to implement the interface.


I won't post the code verbatim, because I don't have it at hand. I can only sketch out its basis from memory

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 to change properties from code. But that's a completely different story)

Scroll to Top