恐怕没有一些代码隐藏是不可能的,但是使用反射和dynamic
,您可以创建一个可以做到这一点的转换器(没有 可能dynamic
,但更复杂):
public class IndexerConverter : IValueConverter
{
public string CollectionName { get; set; }
public string IndexName { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Type type = value.GetType();
dynamic collection = type.GetProperty(CollectionName).GetValue(value, null);
dynamic index = type.GetProperty(IndexName).GetValue(value, null);
return collection[index];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
将以下内容放入资源中:
<local:IndexerConverter x:Key="indexerConverter" CollectionName="Items" IndexName="Index" />
并像这样使用它:
<Label Content="{Binding Converter={StaticResource indexerConverter}}"/>
编辑:当值更改时,以前的解决方案不会正确更新,这个解决方案会:
public class IndexerConverter : IMultiValueConverter
{
public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
{
return ((dynamic)value[0])[(dynamic)value[1]];
}
public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
在资源中:
<local:IndexerConverter x:Key="indexerConverter"/>
用法:
<Label>
<MultiBinding Converter="{StaticResource indexerConverter}">
<Binding Path="Items"/>
<Binding Path="Index"/>
</MultiBinding>
</Label>