0

我对数据绑定有点陌生,并且对如何正确访问数据上下文中的“子”对象有疑问。目前在我的代码中,我有一个简单的视图模型对象:

class MyViewModel
{
    public Dictionary<int, string> seriesChoices = new Dictionary<int, string>();
    ...
}

在主窗口中,如果我直接将视图的数据上下文设置为字典,我可以让数据绑定工作:

ViewModel selectValues = new ViewModel(); 
MyView.DataContext = selectValues.seriesChoices;

....(relevant XAML)

<ComboBox x:Name="ComboBox1" 
              ItemsSource="{Binding}"
              SelectedValuePath="Key"
              DisplayMemberPath="Value"
              />

我想做的是直接将 DataContext 设置为 ViewModel 对象,然后指定底层对象,但我似乎无法让它工作。这是我最近尝试过的事情:

MyView.DataContext = selectValues

....(relevant XAML)

<ComboBox x:Name="ComboBox1" 
          ItemsSource="{Binding seriesChoices}"
          SelectedValuePath="Key"
          DisplayMemberPath="Value"
          />
4

1 回答 1

2

绑定仅适用于属性,因此将您的seriesChoices成员更改为属性并查看是否有效。

class MyViewModel
{
    private Dictionary<int, string> _seriesChoices = new Dictionary<int, string>();

    public Dictionary<int, string> seriesChoices { get { return _seriesChoices; } }

    ...
}

请注意,如果仅使用 getter,则可能必须添加Mode=OneWay到 XAML 中的绑定。

另请注意,如果您希望您的 UI 响应字典中的更改,那是完全不同的蠕虫罐头,请参阅ObservableCollection<>INotifyPropertyChanged

于 2013-10-04T21:34:11.387 回答