nosale
nosale

Reputation: 818

Bind to explicit interface indexer implementation

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

Upvotes: 3

Views: 168

Answers (1)

Rekshino
Rekshino

Reputation: 7325

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?

Upvotes: 3

Related Questions