如何使用键值作为 WPF 中的绑定属性绑定字典



我有这样的类:

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,我想将字典属性 ValuesList<string>的第一个索引显示为列值之一,其中传入的键将是 AccountId。 我的DataGrid ItemSource是来自我的 ViewModel 的 Person 对象的列表,DataGrid有 3 列:PersonIdNameValue(其中 value 是字典项中 List<string> 集合的第一个索引(

我在 stackoverflow 和互联网上的其他地方看到过尝试这样做的例子,但没有一个解决方案对我有用。

这是我的 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} 作为键值的列,但它不起作用。 如果我对有效的帐户 ID 进行硬编码,它可以工作。 以前有人遇到过这种情况吗?

谢谢!

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

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" />

最新更新