'Wpf ListBox with ComboBox databinding problem Dictionary
In my view is a Listbox with a DataTemplate. The DataTemplate defines 2 columns, one for a TextBlock and one for a ComboBox.
The ListBox:
<ListBox ItemsSource="{Binding SelectedSensorProperty.ValueList}" Margin="5" Grid.Row="0"
ScrollViewer.VerticalScrollBarVisibility="Visible">
The ComboBox is defined as follows:
<ComboBox MinWidth="150"
ItemsSource="{Binding Path=DataContext.SelectedSensorProperty.PossibleValuesList,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"
SelectedValuePath="Key"
DisplayMemberPath="Value"
SelectedValue="{Binding Path=Value, Mode=OneWay}"
Grid.Column="1"
Margin="2,0,0,0"/>
My ViewModel contains a variable SelectedSensorProperty of type SensorProperty.
public class SensorProperty
{
public string Name { get; set; }
// key = index value, value = index text
public Dictionary<string, string> PossibleValuesList { get; set; }
// key = feature value, value = index value
public Dictionary<string, string> ValueList { get; set; }
public SensorProperty()
{
ValueList = new Dictionary<string, string>();
}
}
Suppose ValueList contains three KeyValue pairs, then 3 comboxes are shown. The problem is that the selected combobox values are not written to the ValueList. Setting the binding of the combobox to TwoWay gives an error saying the Dictionary is readonly. How to solve this?
Solution 1:[1]
You either need to bind the ValuesList ListBox to the selected item of the PossibleValuesList, or catch the SelectionChanged event of the PossibleValuesList and then update the ValuesList dictionary. In both cases though, you need the dictionaries to notify the UI when something changed in them. That can be done by implementing the INotifyPropertyChanged interface, or the dictionaries to be an ObservableCollection instead.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | funatparties |

