wpf - 绑定(bind)驱动的索引属性不返回

标签 wpf binding indexed-properties

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/

相关文章:

wpf - 如何在wpf弹出控件中使用进度条?

haskell - 如何为此类型创建可存储实例?

c# - 为什么 C# 不实现索引属性?

java - 从索引属性中删除项目 - JavaBeans 问题

ios - 不对 Core Data 属性进行索引的原因是什么?

c# - 从 WPF 中的 Image 标记修改图像

c# - 旋转和打印正方形

c# - 使用哪个 C# 多线程选项

events - Blazor 绑定(bind)行为不一致

c# - 在 Xamarin Forms 中绑定(bind) BackgroundColor 属性 ContentPage