简体   繁体   中英

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM