3

How can I bind to to an explicit interface indexer implementation?

Suppose we have two interfaces

public interface ITestCaseInterface1
{
    string this[string index] { get; }
}

public interface ITestCaseInterface2
{
    string this[string index] { get; }
}

a class implementing both

public class TestCaseClass : ITestCaseInterface1, ITestCaseInterface2
{
    string ITestCaseInterface1.this[string index] => $"{index}-Interface1";

    string ITestCaseInterface2.this[string index] => $"{index}-Interface2";
}

and a DataTemplate

<DataTemplate DataType="{x:Type local:TestCaseClass}">
                <TextBlock Text="**BINDING**"></TextBlock>
</DataTemplate>

What I tried so far without any success

<TextBlock Text="{Binding (local:ITestCaseInterface1[abc])}" />
<TextBlock Text="{Binding (local:ITestCaseInterface1)[abc]}" />
<TextBlock Text="{Binding (local:ITestCaseInterface1.Item[abc])}" />
<TextBlock Text="{Binding (local:ITestCaseInterface1.Item)[abc]}" />

How should my Binding look like?

Thanks

Rekshino
  • 6,954
  • 2
  • 19
  • 44
nosale
  • 808
  • 6
  • 14

1 Answers1

3

You can not in XAML access the indexer, which is explicit implementation of interface.

What you can is to write for each interface a value converter, use appropriate converter in binding and set ConverterParameter to the desired Key:

public class Interface1Indexer : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (value as ITestCaseInterface1)[parameter as string];
    }

    public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException("one way converter");
    }
}

<TextBlock Text="{Binding Converter={StaticResource interface1Indexer}, ConverterParameter='abc'" />

And of course bound properties have to be public, whereas explicit implementation has special state. This question can be helpful: Why Explicit Implementation of a Interface can not be public?

Rekshino
  • 6,954
  • 2
  • 19
  • 44
  • First of all thanks for your answer and time. I was hoping that I missed something, cause with properties everything works fine. Strange thing that Indexer won't work. – nosale Dec 06 '18 at 17:45
  • 1
    @nosale The normal `public` indexer will work, the explicit implementation of interface for indexer will not work. – Rekshino Dec 07 '18 at 07:12