DataBinding与Dictionary索引器

时间:2016-04-20 12:49:11

标签: c# dictionary mvvm data-binding win-universal-app

我是UWP和MVVM的新手。

我在使用DataBinding方面遇到了一些麻烦。

我有一个属性

public System.DayOfWeek CurrentDayOfWeek 

和字典

public MyDictionary Dictionary<System.DayOfWeek,List<String>>

我想将ListView的ItemSource绑定到MyDictionary [CurrentDayOfWeek]

这就是我所挣扎的:

视图模型:

public Dictionary<System.DayOfWeek,List<string>> MyDictionary
{
    get;set;
}
public System.DayOfWeek CurrentDayOfWeek {get;set;}
public List<System.DayOfWeek> DayOfWeeks {get;set;}
.....        

XAML:

    <ComboBox  SelectedItem="{Binding CurrentDayOfWeek,Mode=TwoWay}"
    <ListView ItemSource="{Binding MyDictionary[CurrentDayOfWeek]}"
    >

这不起作用。

我必须在我的viewmodel中添加一些额外的属性才能使其成为一种解决方法,但我觉得它太难看了。

我想知道是否有任何优雅的解决方案?

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试在组合框中显示字典的,然后 Binding ElementName 将在组合框项目中为您提供选择以定义ListView绑定

                <ComboBox x:Name="DropDown"
                   ItemsSource="{Binding ViewModel.CurrentDayOfWeek}"
                   DisplayMemberPath ="Key"
                   SelectedValuePath ="Value"
                   IsReadOnly="True"></ComboBox>

                <ListView x:Name="List"
                   ItemsSource="{Binding ElementName = DropDown, Path = SelectedValue}"
                   DisplayMemberPath ="Value"
                   SelectedValuePath ="Value"/>