Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind to explicit interface indexer implementation

Tags:

c#

wpf

xaml

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

like image 643
nosale Avatar asked Aug 05 '26 19:08

nosale


1 Answers

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?

like image 135
Rekshino Avatar answered Aug 08 '26 11:08

Rekshino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!