I change a ComboBox ItemsSource
(named Tipo
) dynamically on code-behind, due to the value of another ComboBox (which value is saved on currentTipologia
), binding the control later:
int? currentTipologia = data.Difetti[selectedDifettoIndex].Tipologia;
int? currentTipo = data.Difetti[selectedDifettoIndex].Tipo;
Tipo.ItemsSource = currentTipologia == 1 ? listTipoTipologia1 : listTipoTipologia0;
Tipo.DisplayMemberPath = "DisplayValue";
Tipo.SelectedValuePath = "Value";
Tipo.SetBinding(ComboBox.SelectedValueProperty, new Binding
{
Source = data,
Path = new PropertyPath($"Difetti[{selectedDifettoIndex}].Tipo"),
});
data.Difetti[selectedDifettoIndex].Tipo = currentTipologia != selectedValue ? null : currentTipo;
The problem is: when I switch ItemsSource
(passing from value 0/1/2 for example to value 3/4), Tipo
is still binded to a prev Difetti[].Tipo, and it becomes null (erasing its value, which I don’t want).
How can I totally unbind before change ItemsSource? Tried BindingOperations.ClearBinding(Tipo, ComboBox.ItemsSourceProperty);
but has no effect; on this line:
Tipo.ItemsSource = currentTipologia == 1 ? listTipoTipologia1 : listTipoTipologia0;
the Tipo
(which is int?) of another index array becaome null. What’s the correct way to manage this?