C# 绑定到显式接口索引器实现
如何绑定到显式接口索引器实现 假设我们有两个接口C# 绑定到显式接口索引器实现,c#,wpf,xaml,C#,Wpf,Xaml,如何绑定到显式接口索引器实现 假设我们有两个接口 public interface ITestCaseInterface1 { string this[string index] { get; } } public interface ITestCaseInterface2 { string this[string index] { get; } } 实现两者的类 public class TestCaseClass : ITestCaseInterface1, ITestC
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 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]}" />
我的绑定应该是什么样子
谢谢您不能在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'" />
公共类接口索引器:IValueConverter
{
公共对象转换(对象值、类型targetType、对象参数、CultureInfo区域性)
{
返回(值为ITestCaseInterface1)[参数为字符串];
}
公共对象转换回(对象值、类型targetTypes、对象参数、CultureInfo区域性)
{
抛出新的NotImplementedException(“单向转换器”);
}
}
当然,绑定属性必须是公共的,而显式实现有特殊的状态。这个问题很有帮助:您使用的是哪个.Net版本?@LittleBit 4.6.2首先感谢您的回答和时间。我希望我错过了什么,因为在这里一切都很好。奇怪的是索引器不能工作。@如果正常的public
索引器可以工作,那么索引器接口的显式实现就不能工作。