Public Class View
Public Property Items As String() = {"One", "Two", "Three"}
Public Property Index As Integer = 0
End Class
它的实例设置为此 XAML 的 DataContext:
<Window>
<StackPanel>
<ListBox ItemsSource="{Binding Items}" SelectedIndex="{Binding Index}"/>
<Label Content="{Binding Items[Index]}"/>
</StackPanel>
</Window>
但这行不通。
<Label Content="{Binding Items[{Binding Index}]}"/>
这也不是。
<Label Content="{Binding Items[0]}"/>
这有效。
除了在 View 中添加额外的属性之外,还有其他解决方案吗?直接用 XAML 编写的东西?
最佳答案
恐怕没有一些代码隐藏,而是使用反射和 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>
关于wpf - 绑定(bind)驱动的索引属性不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5766490/