如何在 WPF 中绑定键值为绑定 属性 的字典?

How to Bind a Dictionary with the Key value being a Binding Property in WPF?

我有一个 class 这样的:

public class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public int AccountId { get; set; }
    public Dictionary<int, List<string>> Values { get; set; }
}

我的 XAML 中有一个 DataGrid,我想在其中显示字典 属性 Values[ 中 List<string> 的第一个索引=38=] 作为列值之一,其中传递的键将是 AccountId。我的 DataGridItemSource 是来自我的 ViewModel 的 Person 对象列表,DataGrid 有 3 列,PersonIdNameValue(其中value是字典项中List<string>集合的第一个索引)

我在 Whosebug 和互联网上的其他地方看到了尝试这样做的示例,但 none 的解决方案对我有用。

这是我的 XAML 代码:

<DataGrid Name="MyDataGrid" ItemsSource="{Binding Persons}">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="ID">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding PersonId}" IsEnabled="False" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Name">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Name}" IsEnabled="False" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Value">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Values[{Binding AccountId}][0]}" IsEnabled="False" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

最后一列是我尝试使用 {Binding} 作为键值的列,但它不起作用。如果我硬编码一个有效的 AccountId,它就可以工作。有人遇到过这个吗?

谢谢!

视图模型的目的之一是以方便的格式提供数据以供查看。通过键从字典中获取值的代码,然后 return 第一项可以写在视图模型中,而不是转换器中:

public class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public int AccountId { get; set; }
    public Dictionary<int, List<string>> Values { get; set; }

    public string AccountIdValue { get { return Values[AccountId].FirstOrDefault(); } }
}

然后绑定到那个助手 属性:

<TextBox Text="{Binding AccountIdValue}" IsEnabled="False" />