Reputation: 167
I'm a bit new to data-binding and had a question about how to properly access "child" objects within the data context. In my code currently I have a simple view model object:
class MyViewModel
{
public Dictionary<int, string> seriesChoices = new Dictionary<int, string>();
...
}
In the Main Window, if I set the data context of the view to the dictionary directly, I am able to get data-binding to work:
ViewModel selectValues = new ViewModel();
MyView.DataContext = selectValues.seriesChoices;
....(relevant XAML)
<ComboBox x:Name="ComboBox1"
ItemsSource="{Binding}"
SelectedValuePath="Key"
DisplayMemberPath="Value"
/>
What I would like to do is set the DataContext to the ViewModel object directly, and then specify underlying objects, but I can't seem to get this to work. This is the most recent thing I have tried:
MyView.DataContext = selectValues
....(relevant XAML)
<ComboBox x:Name="ComboBox1"
ItemsSource="{Binding seriesChoices}"
SelectedValuePath="Key"
DisplayMemberPath="Value"
/>
Upvotes: 0
Views: 85
Reputation: 5976
Bindings only work on properties, so change your seriesChoices
member into a property and see if that works.
class MyViewModel
{
private Dictionary<int, string> _seriesChoices = new Dictionary<int, string>();
public Dictionary<int, string> seriesChoices { get { return _seriesChoices; } }
...
}
Note that if you use a getter only, you may have to add Mode=OneWay
to the binding in XAML.
Also note that if you want your UI to respond to changes in the dictionary, that is a whole other can of worms, see ObservableCollection<>
and INotifyPropertyChanged
Upvotes: 2