绑定到显式接口索引器实现

3

如何绑定到显式接口索引器实现?

假设我们有两个接口

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

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

一个同时实现两个功能的类
public class TestCaseClass : ITestCaseInterface1, ITestCaseInterface2
{
    string ITestCaseInterface1.this[string index] => $"{index}-Interface1";

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

和一个DataTemplate

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

我尝试过以下方法,但都没有成功:
<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]}" />

我的 Binding 应该长什么样子?

谢谢


你正在使用哪个 .Net 版本? - LittleBit
@LittleBit 4.6.2 - nosale
1个回答

3

您无法在XAML中访问索引器,因为它是接口的显式实现。

您可以为每个接口编写一个值转换器,在绑定中使用适当的转换器,并将ConverterParameter设置为所需的键:

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'" />

当然,绑定属性必须是public,而显式实现具有特殊状态。这个问题可能会有所帮助:为什么接口的显式实现不能是公共的?


首先感谢您的回答和时间。我原本希望是自己漏看了什么,因为使用属性时一切正常。但奇怪的是索引器不起作用。 - nosale
1
@nosale 正常的 public 索引器可以工作,但是索引器的显式接口实现将无法工作。 - Rekshino

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接