如何绑定到显式接口索引器实现?
假设我们有两个接口
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
应该是什么样子?
感谢
您不能在XAML中访问索引器,这是接口的显式实现。
您可以为每个接口编写一个值转换器,在绑定中使用适当的转换器,并将ConverterParameter
设置为所需的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'" />
当然,绑定属性必须是public
,而显式实现具有特殊状态。这个问题可能很有帮助:为什么接口的显式实现不能是公共的?